5

我一直在尝试将两个符号之间的文本替换为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
4

5 回答 5

8

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

$start = '\[';
$end  = '\]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);
于 2013-02-12T12:14:21.810 回答
1

some functions that may help

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

and

function getAllBetweenStr($string, $start, $end)
    {
        preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
        return $matches[1];
    }
于 2013-02-12T12:28:56.247 回答
1

怎么样

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

应该让步normal text [test] after text

编辑

小提琴演示在这里

于 2013-02-12T12:19:25.233 回答
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
于 2013-02-12T12:15:17.627 回答
0

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

<?php
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
?>
于 2013-02-12T12:20:18.653 回答