2015-05-30 44 views
-1

从这样的字符串:如何获得从一开始到第二个逗号的子字符串?

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

我需要的字符,直到倒数第二TNE逗号:

$b = "Viale Giulio Cesare, 137, Roma"; 

如何删除一切找到倒数第二个逗号?

+4

你有没有尝试过或做过一些研究? – Rizier123

+0

是的我发现这个http://stackoverflow.com/questions/10862048/how-to-remove-part-of-a-string-after-last-comma-in-php但我需要抓倒数第二个逗号 – Cloud78

+0

所以...你做了什么?为什么这个问题的答案不能帮助你? – GolezTrol

回答

3

这应该为你工作:

在这里,我第一次得到你的字符串中的最后一个逗号与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 
0

在众多的其他可能的解决方案,你可以使用以下命令:

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

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

您可以使用explode将项目拆分为逗号来将其转换为数组。那么你可以修改使用array_spliceimplode数组的数组回到一起为一个字符串:

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

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

+1

*不是单行*您可以将所有内容放在同一行中,但如果您编写如此长的代码行,则始终存在可读性问题。 (顺便说一句:我也想过发布这个解决方案,但后来我用'strrpos()'发布了一个;清晰易懂的解释✓) – Rizier123

+0

没有一个*声明*,我的意思是。 :) – GolezTrol

相关问题