2010-05-19 41 views
7

完成以下操作的最佳方式是什么?PHP爆炸并设置为空字符串丢失件

我有一个字符串格式为:

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

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

因为我需要exctract名称/类型separetly,我做的:

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

是否有更简单(聪明任何更快)的方式来做到这一点,而不必做isset($temp[1])count($temp)

谢谢!

+0

不要这样想,如果你试图访问你会得到一个异常/错误'[1]'没有检查。 – Aren 2010-05-19 16:10:34

+0

这看起来像是最有效的解决方案。 – EAMann 2010-05-19 16:14:01

回答

7
list($name, $type) = explode('|', s1.'|'); 
+0

好办法处理潜在的通知,并且一个空字符串而不是null – 2010-05-19 16:22:50

+0

不错的技巧,+1,非常有趣 – 2010-05-19 17:10:24

-1
if(strstr($temp,"|")) 
{ 
    $temp = explode($s1, '|'); 
    $name = $temp[0]; 
    $type = $temp[1]; 
} 
else 
{ 
    $name = $temp[0]; 
    //no type 
} 

也许吧?

+1

只是单挑:如果你想要做的只是检查一个针串是干草堆串,那么你应该使用'strpos()!== false',它比'strstr()'快得多, 。 – pinkgothic 2010-05-19 17:21:13

4

注意的论据爆炸(顺序)

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

$类型将是NULL为$ S3,但它会给通知

+0

仍然需要检查类型是否为空,并且如果是,则将''赋值给它,但如果是这样的话,则为 – 2010-05-19 16:19:11

+3

:@list($ name,$ type)= explode('|',$ s1),通知将被吞噬。 @Thomas - 利用php的无类型特性,并允许php根据其使用情况输入null值。 – 2010-05-19 16:27:13

+0

好点kevin,我站在更正 – 2010-05-19 16:35:06

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"; 
+0

来测试,你在爆炸中使用的2个限制,为什么? – 2010-05-19 17:08:30

+0

@Marco它只是以防万一...... – Cristian 2010-05-19 17:11:43

+0

你是对的,但实际上在开发过程中,我使用'error_reporting(E_ALL);'和'$ str ='name''时,调用'list($ name,$ type )'上升PHP错误'注意:未定义偏移量:1' – 2011-05-06 19:00:28

3

我的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); 
+0

有趣的一点,但我认为使用'list'是更简洁。 – 2011-05-06 18:52:53