如何获得子字符串从开始直到第二个最后一个逗号


How to get the sub string from the start until the second last comma?

从这样的字符串:

$a = "Viale Giulio Cesare, 137, Roma, RM, Italia";

我需要得到直到倒数第二个逗号的字符串:

$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

您可以使用explode将项目转换为逗号分隔的数组。然后您可以使用array_spliceimplode修改数组,将数组重新组合为字符串:

<?php
$a = "Viale Giulio Cesare, 137, Roma, RM, Italia";
$l = explode(',', $a);
array_splice($l, -2);
$b = implode(',', $l);

不是一行,而是一个非常直接的解决方案。

在许多其他可能的解决方案中,您可以使用以下方法:

<?php
$re = "~(.*)(?:,.*?,.*)$~"; 
$str = "Viale Giulio Cesare, 137, Roma, RM, Italia"; 
preg_match($re, $str, $matches);
echo $matches[1]; // output: Viale Giulio Cesare, 137, Roma
?>