从这样的字符串:如何获得从一开始到第二个逗号的子字符串?
$a = "Viale Giulio Cesare, 137, Roma, RM, Italia";
我需要的字符,直到倒数第二TNE逗号:
$b = "Viale Giulio Cesare, 137, Roma";
如何删除一切找到倒数第二个逗号?
从这样的字符串:如何获得从一开始到第二个逗号的子字符串?
$a = "Viale Giulio Cesare, 137, Roma, RM, Italia";
我需要的字符,直到倒数第二TNE逗号:
$b = "Viale Giulio Cesare, 137, Roma";
如何删除一切找到倒数第二个逗号?
这应该为你工作:
在这里,我第一次得到你的字符串中的最后一个逗号与strrpos()
。然后,从这个子字符串中搜索最后一个逗号,然后是倒数第二个逗号。通过第二个逗号的这个位置,我得到整个字符串的substr()
。
echo substr($a, 0, strrpos(substr($a, 0, strrpos($a, ",")), ","));
//^^^^^^ ^^^^^^^ ^^^^^^ ^^^^^^^
//| | | |1.Returns the position of the last comma from $a
//| | |2.Get the substr() from the start from $a until the last comma
//| |3.Returns the position of the last comma from the substring
//|4.Get the substr from the start from $a until the position of the second last comma
在众多的其他可能的解决方案,你可以使用以下命令:
<?php
$re = "~(.*)(?:,.*?,.*)$~";
$str = "Viale Giulio Cesare, 137, Roma, RM, Italia";
preg_match($re, $str, $matches);
echo $matches[1]; // output: Viale Giulio Cesare, 137, Roma
?>
您可以使用explode
将项目拆分为逗号来将其转换为数组。那么你可以修改使用array_splice
和implode
数组的数组回到一起为一个字符串:
<?php
$a = "Viale Giulio Cesare, 137, Roma, RM, Italia";
$l = explode(',', $a);
array_splice($l, -2);
$b = implode(',', $l);
不是单行线,而是一个非常直接的解决方案。
你有没有尝试过或做过一些研究? – Rizier123
是的我发现这个http://stackoverflow.com/questions/10862048/how-to-remove-part-of-a-string-after-last-comma-in-php但我需要抓倒数第二个逗号 – Cloud78
所以...你做了什么?为什么这个问题的答案不能帮助你? – GolezTrol