【问题标题】:PHP preg_match get in between stringPHP preg_match 在字符串之间
【发布时间】:2012-11-13 12:27:47
【问题描述】:

我正在尝试获取字符串hello world

这是我目前得到的:

$file = "1232#hello world#";

preg_match("#1232\#(.*)\##", $file, $match)

【问题讨论】:

  • 您能否提供更多您尝试匹配的字符串示例?
  • 对不起双反斜杠。我想我需要再添加一个反斜杠以使其可见。

标签: php regex preg-match


【解决方案1】:

如果您希望分隔符也包含在数组中,这对于 preg_split 会更有用,因为您可能不希望每个数组元素都以分隔符开始和结束,我即将展示的示例将包括数组值内的分隔符。这就是你需要的preg_match('/\#(.*?)#/', $file, $match); print_r($match); 这将输出array( [0]=> #hello world# )

【讨论】:

    【解决方案2】:

    建议使用除# 以外的分隔符,因为您的字符串包含#,并且使用非贪婪的(.*?) 来捕获# 之前的字符。顺便说一句,# 如果不是分隔符,则不需要在表达式中进行转义。

    $file = "1232#hello world#";
    preg_match('/1232#(.*?)#/', $file, $match);
    
    var_dump($match);
    // Prints:
    array(2) {
      [0]=>
      string(17) "1232#hello world#"
      [1]=>
      string(11) "hello world"
    }
    

    更好的是使用[^#]+(或*而不是+,如果字符可能不存在)来匹配所有字符直到下一个#

    preg_match('/1232#([^#]+)#/', $file, $match);
    

    【讨论】:

    • 这太快了,谢谢!
    【解决方案3】:

    使用环视:

    preg_match("/(?<=#).*?(?=#)/", $file, $match)
    

    演示:

    preg_match("/(?<=#).*?(?=#)/", "1232#hello world#", $match);
    print_r($match)
    

    输出:

    Array
    (
        [0] => hello world
    )
    

    测试它here

    【讨论】:

    • preg_match("/(?&lt;=#)[^#]*(?=#)/", $file, $match); 也可以
    • 你能解释一下它是如何工作的吗?没关系,但我不明白 (?
    • @KrzysztofJarosz - (?&lt;=#) 是正向后视,意味着匹配在# 之前,而(?=#) 是正向前瞻,意味着匹配后跟#。有关环视零长度断言的更多信息,请参阅regular-expressions.info/lookaround.html
    【解决方案4】:
    preg_match('/1232#(.*)#$/', $file, $match);
    

    【讨论】:

      【解决方案5】:

      在我看来你只需要得到$match[1]

      php > $file = "1232#hello world#";
      php > preg_match("/1232\\#(.*)\\#/", $file, $match);
      php > print_r($match);
      Array
      (
          [0] => 1232#hello world#
          [1] => hello world
      )
      php > print_r($match[1]);
      hello world
      

      你得到不同的结果了吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 2012-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多