I have a string:
我有一个字符串:
$var = "[Item 1],[Item 2],[Item, 3]";
When I use explode:
当我使用爆炸时:
$var = explode(",", $var);
This also explodes out the comma inside the square brackets.
这也会爆出方括号内的逗号。
I would like to return:
我想回复:
[Item 1]
[Item 2]
[Item, 3]
Running through a foreach () {} statement which I am using. Any ideas?
运行我正在使用的foreach(){}语句。有任何想法吗?
3 个解决方案
#1
$var = "[Item 1],[Item 2],[Item, 3]";
$var = explode("],[", $var);
print_r($var);
--doh forgot that the delimiter is lost so um a crude option to put those [] back in:
- 忘了分隔符丢失所以这是一个粗略的选择,把那些[]放回去:
<?php
$var = "[Item 1],[Item 2],[Item, 3]";
$var = explode("],[", $var);
foreach ($var as $v){
if(substr($v,0,1)!='['){
$v='['.$v;
}
if(substr($v,-1)!=']'){
$v=$v.']';
}
$out[]=$v;
}
echo '<pre>';
print_r($out);
may be better to switch to a regular expression split, i'll write that in a sec
可能会更好地切换到正则表达式拆分,我会在一秒钟内写出来
FINIAL sexy answer:
最佳性感答案:
<?php
$var = "[Item 1],[Item 2],[Item, 3]";
$var = preg_split('/(\B,\B)/', $var);
echo '<pre>';
print_r($var);
#2
It will not work which you want. But it can be done with
它不会工作你想要的。但它可以完成
$var = "[Item 1],[Item 2],[Item, 3]";
$varArr = explode("],", $var);
$newArr= array();
foreach($varArr as $key=>$val)
$newArr[$key] = $val . "]";
echo "<pre>";
print_r($newArr);
echo "</pre>";
#3
How about using regular expression to extract those information?
如何使用正则表达式提取这些信息?
$var = "[Item 1],[Item 2],[Item, 3]";
preg_match_all("(\[.+?\])", $var, $result);
print_r($result[0]);
#1
$var = "[Item 1],[Item 2],[Item, 3]";
$var = explode("],[", $var);
print_r($var);
--doh forgot that the delimiter is lost so um a crude option to put those [] back in:
- 忘了分隔符丢失所以这是一个粗略的选择,把那些[]放回去:
<?php
$var = "[Item 1],[Item 2],[Item, 3]";
$var = explode("],[", $var);
foreach ($var as $v){
if(substr($v,0,1)!='['){
$v='['.$v;
}
if(substr($v,-1)!=']'){
$v=$v.']';
}
$out[]=$v;
}
echo '<pre>';
print_r($out);
may be better to switch to a regular expression split, i'll write that in a sec
可能会更好地切换到正则表达式拆分,我会在一秒钟内写出来
FINIAL sexy answer:
最佳性感答案:
<?php
$var = "[Item 1],[Item 2],[Item, 3]";
$var = preg_split('/(\B,\B)/', $var);
echo '<pre>';
print_r($var);
#2
It will not work which you want. But it can be done with
它不会工作你想要的。但它可以完成
$var = "[Item 1],[Item 2],[Item, 3]";
$varArr = explode("],", $var);
$newArr= array();
foreach($varArr as $key=>$val)
$newArr[$key] = $val . "]";
echo "<pre>";
print_r($newArr);
echo "</pre>";
#3
How about using regular expression to extract those information?
如何使用正则表达式提取这些信息?
$var = "[Item 1],[Item 2],[Item, 3]";
preg_match_all("(\[.+?\])", $var, $result);
print_r($result[0]);