【问题标题】:PHP explode and set to empty string the missing piecesPHP 爆炸并设置为空字符串丢失的部分
【发布时间】:2011-02-21 11:28:09
【问题描述】:

完成以下任务的最佳方法是什么。

我有这种格式的字符串:

$s1 = "name1|type1"; //(pipe is the separator)
$s2 = "name2|type2";
$s3 = "name3"; //(in some of them type can be missing)

假设nameN / typeN 是字符串,它们不能包含管道。

因为我需要单独提取名称/类型,所以我这样做:

$temp = explode('|', $s1);
$name = $temp[0];
$type = ( isset($temp[1]) ? $temp[1] : '' );

有没有一种更简单(更智能,更快)的方法来做到这一点,而不必这样做 isset($temp[1])count($temp)

谢谢!

【问题讨论】:

  • 别这么想,如果你不先检查就尝试访问[1],你会得到一个异常/错误。
  • 这看起来已经是最有效的解决方案了。

标签: php explode


【解决方案1】:

我是array_pop()array_shift() 的粉丝,如果它们使用的数组为空,它们不会出错。

在你的情况下,那将是:

$temp = explode('|', $s1);
$name = array_shift($temp);
// array_shift() will return null if the array is empty,
// so if you really want an empty string, you can string
// cast this call, as I have done:
$type = (string) array_shift($temp);

【讨论】:

    【解决方案2】:
    list($name, $type) = explode('|', s1.'|');
    

    【讨论】:

    • 处理潜在通知的好技巧,以及一个空字符串而不是空字符串
    【解决方案3】:

    没有必要做isset 因为 $temp[1] 将存在并且内容为空值。这对我来说很好:

    $str = 'name|type';
    
    // if theres nothing in 'type', then $type will be empty
    list($name, $type) = explode('|', $str, 2);
    echo "$name, $type";
    

    【讨论】:

    • 我不明白你在explode中使用的2限制,为什么?
    • 你是对的,但实际上在开发过程中我使用error_reporting(E_ALL); 而当$str='name' 时,对list($name, $type) 的调用会引发PHP 错误Notice: Undefined offset: 1
    【解决方案4】:

    注意explode()的参数顺序

    list($name,$type) = explode( '|',$s1);
    

    对于 $s3,$type 将为 NULL,但它会发出 通知

    【讨论】:

    • 仍然需要检查 type 是否为 null,如果是,则为其分配 ' '
    • 如果你这样做:@list($name,$type) = explode('|', $s1),通知会被吞掉。 @Thomas - 利用 php 的无类型特性并允许 php 根据其使用情况对空值进行类型处理。
    • @Mark Ba​​ker:我更新了问题中的代码,谢谢你告诉我。
    • @Marco 使用 Stef 的附加 |除非有真正的 $type 值,否则在爆炸之前保证 $type 中没有通知和空字符串
    • @Kevin Vaughan:+1 表示您的评论,但我做了一个测试:确实,使用您的解决方案list 将不会在$type 丢失时再触发通知,但$type仍将设置为 NULL 而不是空字符串,您可以使用简单的 var_dump($type); 进行测试
    【解决方案5】:
    if(strstr($temp,"|"))
    {
       $temp = explode($s1, '|');
       $name = $temp[0];
       $type = $temp[1];
    }
    else
    {
       $name = $temp[0];
       //no type
    }
    

    也许?

    【讨论】:

    • 请注意:如果您只想检查针线是否在大海捞针中,那么您应该使用strpos() !== false,它比strstr() 快得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2011-12-10
    • 2011-07-20
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多