【问题标题】:Select text content between elements选择元素之间的文本内容
【发布时间】:2013-09-01 03:36:41
【问题描述】:

如何选择文本元素之间的内容?比如在这个文本中我要选择[]之间的内容:

大家好[我只想选择这个部分,仅此而已]。你好。你好吗? zzzzzzzzz zzzzzzzzzzzz

如果我在文本中包含此文本,我可以使用:

<?php
 $a=file("text.txt");
 print "".$a[]."";
?>

我可以使用explode,但问题是explode 不适用于两个或更多字符。

【问题讨论】:

    标签: php character explode


    【解决方案1】:

    要获取 [] 之间的内容,请使用以下正则表达式:'[(.*)]'

    示例代码:

    $var = "Helo everybody [ Only i need this select no more ] , hi how are you zzzzzzzzz zzzzzzzzzzzz";
    
    $matches = array();
    $t = preg_match_all('/\[(.*)\]/s', $var, $matches);
    print_r($matches[1]);
    

    Eval

    【讨论】:

    • 如果我有更多的文本,里面有更多的 []?
    • 在这种情况下,只需将 preg_match 更改为 preg_match_all
    【解决方案2】:

    给你一个例子

    <?php
    
    $s = 'Helo [everybody] [Only i need this select no more], hi [how] are you zzzzzz';
    
    if (preg_match_all("^\[(.*?)\]^", $s, $matches, PREG_OFFSET_CAPTURE)) {
        foreach ($matches[1] as $match) {
           echo $match[0]."<br/>";
        }
    }
    
    ?>
    

    【讨论】:

      【解决方案3】:
      <?php
      $str = "Hello everybody [ I want to select only this section, nothing more ]. Hi. How are you? zzzzzzzzz zzzzzzzzzzzz";
      $from = "[";
      $to = "]";
      
      echo getBetween($str,$from,$to);
      
      function getBetween($str,$from,$to)
      {
          return substr(substr($str,strpos($str,$from),strlen($str)),1,strpos(substr($str,strpos($str,$from),strlen($str)),$to)-1);
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        • 2013-05-18
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 2014-12-04
        相关资源
        最近更新 更多