【问题标题】:How to get the sub string from the start until the second last comma?如何从开始到倒数第二个逗号获取子字符串?
【发布时间】:2015-05-30 14:35:36
【问题描述】:

来自这样的字符串:

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

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

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

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

【问题讨论】:

  • 你有没有尝试过或做过一些研究?
  • 是的,我找到了这个stackoverflow.com/questions/10862048/…,但我需要抓住倒数第二个逗号
  • 那么...你用它做了什么?为什么那个问题的答案对你没有帮助?
  • 因为我没有阅读答案..我自己尝试了一些东西..并不总是在 stackoverflow 上等待
  • @Cloud78 我自己尝试了一些事情将您的代码/尝试复制并粘贴到您的问题中,说出您得到的输出以及您的期望。

标签: php string substring


【解决方案1】:

这应该适合你:

在这里,我首先使用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

【讨论】:

    【解决方案2】:

    您可以使用explode 将项目转换为数组,方法是用逗号分隔。然后您可以使用array_spliceimplode 将数组修改为一个字符串:

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

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

    【讨论】:

    • 不是一行 好吧,您可以将所有内容放在一行中,但是如果您编写如此长的代码行,则始终是可读性问题。 (顺便说一句:我也想过将其发布为解决方案,但后来我发布了strrpos();清晰易懂的解释✓)
    • 不是一个语句,我的意思是。 :)
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2022-06-17
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 2015-12-14
      • 2014-05-19
      相关资源
      最近更新 更多