PHP 爆炸并将缺失的部分设置为空字符串
完成以下任务的最佳方法是什么。
我有这种格式的字符串:
$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])< /code> 或
count($temp)
。
谢谢!
What's the best way to accomplish the following.
I have strings in this format:
$s1 = "name1|type1"; //(pipe is the separator)
$s2 = "name2|type2";
$s3 = "name3"; //(in some of them type can be missing)
Let's assume nameN
/ typeN
are strings and they can not contain a pipe.
Since I need to exctract the name / type separetly, I do:
$temp = explode('|', $s1);
$name = $temp[0];
$type = ( isset($temp[1]) ? $temp[1] : '' );
Is there an easier (smarter whatever faster) way to do this without having to do isset($temp[1])
or count($temp)
.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请注意,对于 $s3,explode() $type 的参数顺序
将为 NULL,尽管它会给出通知
Note the order of arguments for explode()
$type will be NULL for $s3, though it will give a Notice
我是
array_pop()
和array_shift()
,如果它们使用的数组为空,则不会出错。在你的情况下,那就是:
I'm a fan of
array_pop()
andarray_shift()
, which don't error out if the array they use is empty.In your case, that would be:
不需要执行isset,因为$temp[1]将存在并且内容为空值。这对我来说效果很好:
There is not need to do
isset
since $temp[1] will exist and content an empty value. This works fine for me:或许?
Maybe?