【问题标题】:Get string between two characters in php获取php中两个字符之间的字符串
【发布时间】:2014-07-18 09:59:20
【问题描述】:

我在 php 中有一个字符串说

$string = 'All I want to say is that <#they dont really care#> about us.
    I am wasted away <#I made a million mistake#>, am I too late. 
    Theres a storm in my head and a race on my bed, <#when you are not near#>' ;


$expected_output = array(
    'they dont really care',
    'I made a million mistake',
    'when you are not near'
);

如何使用 PHP regex 实现这一点? 感谢阅读:)

【问题讨论】:

    标签: php regex preg-match preg-match-all pcre


    【解决方案1】:

    这段代码会做你想做的事

    <?php
    
    $string = 'All I want to say is that <#they dont really care#> about us.
        I am wasted away <#I made a million mistake#>, am I too late. 
        Theres a storm in my head and a race on my bed, <#when you are not near#>' ;
    
    
    preg_match_all('/<#(.*)#>/isU', $string, $matches);
    
    var_dump($matches[1]);
    

    【讨论】:

      【解决方案2】:

      更紧凑的版本:

      $regex = '~<#\K.*?(?=#>)~';
      preg_match_all($regex, $string, $matches);
      print_r($matches[0]);
      

      查看the regex demo中的匹配项。

      匹配项

      they dont really care
      I made a million mistake
      when you are not near
      

      说明

      • ^ 锚断言我们位于字符串的开头
      • &lt;# 匹配左分隔符
      • \K 告诉引擎从它返回的最终匹配中删除匹配的内容
      • .*? 懒惰地将字符匹配到...
      • 前瞻(?=#&gt;) 可以断言后面是#&gt;
      • $ 锚断言我们在字符串的末尾

      参考

      【讨论】:

        【解决方案3】:

        通过前瞻和后瞻,

        (?<=<#).*?(?=#>)
        

        最后调用preg_match_all函数打印匹配的字符串。

        您的 PHP 代码将是,

        <?php
        $data = 'All I want to say is that <#they dont really care#> about us.
            I am wasted away <#I made a million mistake#>, am I too late. 
            Theres a storm in my head and a race on my bed, <#when you are not near#>' ;
        $regex =  '~(?<=<#).*?(?=#>)~';
        preg_match_all($regex, $data, $matches);
        var_dump($matches);
        ?>
        

        输出:

        array(1) {
          [0]=>
          array(3) {
            [0]=>
            string(21) "they dont really care"
            [1]=>
            string(24) "I made a million mistake"
            [2]=>
            string(21) "when you are not near"
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-09-12
          • 1970-01-01
          • 2012-12-28
          • 1970-01-01
          • 2013-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多