【问题标题】:Replacing text between two limts替换两个限制之间的文本
【发布时间】:2013-02-12 12:07:53
【问题描述】:

我一直在尝试将两个符号之间的文本替换为preg_replace,但是由于我得到一个空字符串的空输出,所以仍然没有完全正确,这就是我到目前为止所拥有的

p>
$start = '["';
$end   = '"]';
$msg   = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);

所以我正在寻找的示例输出是:

normal text [everythingheregone] after text 

 normal text [test] after text

【问题讨论】:

  • 普通文本和后面的文本总是不变的吗?
  • $start$end 锚点必须是字符串,并且必须进行转义。你使用的是数组,[ 会是个问题。
  • @Bhushan 没有前后文字会改变

标签: php regex


【解决方案1】:

您将 $start 和 $end 定义为数组,但将其用作普通变量。尝试将您的代码更改为:

$start = '\[';
$end  = '\]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);

【讨论】:

    【解决方案2】:

    怎么样

    $str  = "normal text [everythingheregone] after text";
    $repl = "test";
    $patt = "/\[([^\]]+)\]/"; 
    $res  = preg_replace($patt, "[". $repl ."]", $str);
    

    应该让normal text [test] after text

    编辑

    小提琴演示here

    【讨论】:

    • 这也会给出空白输出
    【解决方案3】:

    一些可能有帮助的功能

    function getBetweenStr($string, $start, $end)
        {
            $string = " ".$string;
            $ini = strpos($string,$start);
            if ($ini == 0) return "";
            $ini += strlen($start);    
            $len = strpos($string,$end,$ini) - $ini;
            return substr($string,$ini,$len);
        }
    

    function getAllBetweenStr($string, $start, $end)
        {
            preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
            return $matches[1];
        }
    

    【讨论】:

      【解决方案4】:
      $row['body']= "normal text [everythingheregone] after text ";
      $start = '\[';
      $end = '\]';
      $msg = preg_replace('#'.$start.'.*?'.$end.'#s', '$1 [test] $3', $row['body']);
      //output: normal text [test] after text done
      

      【讨论】:

        【解决方案5】:

        我有一个正则表达式方法。正则表达式为:\[.*?]

        <?php
        $string = 'normal text [everythingheregone] after text ';
        $pattern = '\[.*?]';
        $replacement = '[test]'
        echo preg_replace($pattern, $replacement, $string);
        //normal text [test] after text
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-26
          • 2016-08-16
          • 2021-07-23
          • 2019-12-25
          • 2014-10-24
          • 1970-01-01
          相关资源
          最近更新 更多