php:
$str="M. M. Grice and B. H. Alexander and L. Ukestad ";
// I need to explode the string by delimiter "and"
$output=explode("and",$str);
输出:
M. M. 格里斯
亚历克斯
的
L. 乌克斯塔德
在"亚历山大"这个名字中有一个"和",所以也被拆分了。所以,我把它改成了$output=explode(" and ",$str)// as delimiter "and" has space.
但它不起作用。
我哪里做错了?我试过$output=explode(" and ",$str)
.但他们都没有工作
预期输出:
M. M. 格里斯
亚历山大
L. 乌克斯塔德
问题中提供的代码:
$output=explode(" and ", $str);
是获得所需输出的正确方法。
当输入字符串$str
中and
周围的字符不是常规空格(" " == chr(32)
)而是制表符("t" == chr(9)
),换行符("n" == chr(10)
)或其他空格字符时,它不起作用。
字符串可以使用preg_split()
进行拆分:
$output = preg_split('/sands/', $str);
将使用任何空格字符包围的and
作为分隔符。
可以使用的另一种regex
是:
$output = preg_split('/bandb/', $str);
这将拆分$str
使用单词 and
作为分隔符,无论它周围是什么字符(非字母、非数字、非下划线)。它将and
识别为问题中提供的字符串中的分隔符,但也"M. M. Grice and B. H. Alexander (and L. Ukestad)"
中。
一个不希望的副作用是and
周围的空格不是分隔符的一部分,它们将保留在分割片段中。可以通过修剪 preg_split() 返回的片段轻松删除它们:
$str = "M. M. Grice and B. H. Alexander (and L. Ukestad)";
$output = array_map('trim', preg_split('/bandb/', $str));
var_export($output);
将显示:
array (
0 => 'M. M. Grice',
1 => 'B. H. Alexander (',
2 => 'L. Ukestad)',
)
通过正则表达式更好地尝试一下:preg_split("/\sand\s/i",$str);
万一(AND & and)两者都