我正在使用 php 7.4
并且我有以下字符串:
Tester Test Street 11 (Nursing Home, Example), 1120 New York
'-------------Split String here
'-----------------------NOT HERE
当我执行 explode()
时,我得到:
$addressAll = explode(", ", "Tester Test Street 11 (Nursing Home, Example), 1120 New York");
/*
array(3) {
[0]=>
string "Tester Test Street 11 (Nursing Home"
[1]=>
string "Example)"
[2]=>
string "1120 New York"
}
*/
但是,我想得到:
array(3) {
[0]=>
string "Tester Test Street 11 (Nursing Home, Example)"
[1]=>
string "1120 New York"
}
关于如何只拆分最后一次出现的 ,
的任何建议。
感谢您的回复!
答案 0 :(得分:1)
使用 strrpos()
查找输入字符串中最后一个逗号的位置,使用 substr()
提取位于 befora 之后和最后一个逗号之后的子字符串:
$input = 'Tester Test Street 11 (Nursing Home, Example), 1120 New York';
$pos = strrpos($input, ',');
$prefix = substr($input, 0, $pos);
$suffix = substr($input, $pos + 1);
答案 1 :(得分:1)
带有 preg_split() 的解决方案。 字符串由一个逗号分隔,后面只跟没有逗号的字符,直到字符串的末尾。
$input = 'Tester Test Street 11 (Nursing Home, Example), 1120 New York';
$array = preg_split('~,(?=[^,]+$)~',$input);
?= 导致括号中的表达式不被用作反向引用。