如何从开始到倒数第二个逗号获取子字符串?

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";

如何删除所有找到倒数第二个逗号的内容?

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

<?php
$re = "~(.*)(?:,.*?,.*)$~"; 
$str = "Viale Giulio Cesare, 137, Roma, RM, Italia"; 

preg_match($re, $str, $matches);
echo $matches[1]; // output: Viale Giulio Cesare, 137, Roma
?>

这应该适合你:

在这里我首先得到你字符串中的最后一个逗号和整个字符串的 strrpos(). Then out of this sub string I also search the last comma, which is then the penultimate comma. With this position of the second last comma I just get the 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);

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