7

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

我有这种格式的字符串:

$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).

谢谢!

4

5 回答 5

8
list($name, $type) = explode('|', s1.'|');
于 2010-05-19T16:18:37.737 回答
4

注意 explode() 的参数顺序

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

$s3 的 $type 将为 NULL,尽管它会给出一个通知

于 2010-05-19T16:15:34.463 回答
3

我是 and 的粉丝,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);
于 2010-05-19T17:03:47.843 回答
0

没有必要这样做,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";
于 2010-05-19T16:16:29.937 回答
-1
if(strstr($temp,"|"))
{
   $temp = explode($s1, '|');
   $name = $temp[0];
   $type = $temp[1];
}
else
{
   $name = $temp[0];
   //no type
}

也许?

于 2010-05-19T16:14:59.147 回答