在两个限制之间替换文本

时间:2013-02-12 12:07:53

标签: php regex

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

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

所以我想要的示例输出是:

normal text [everythingheregone] after text 

 normal text [test] after text

5 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

怎么样

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

应该产生normal text [test] after text

修改

小提琴演示here

答案 2 :(得分:1)

可能有帮助的一些功能

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];
    }

答案 3 :(得分:0)

$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

答案 4 :(得分:0)

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

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