在两个限制之间替换文本

5

我一直在尝试使用preg_replace替换两个符号之间的文本,但是仍然没有完全做对,因为我得到了一个空字符串的null输出。以下是我目前的代码:

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

所以我需要的例子输出如下:
normal text [everythingheregone] after text 

To

 normal text [test] after text

普通文本和后续文本是否总是不变的? - Bhushan Firake
1
$start$end锚点必须是字符串,并且必须进行转义。您正在使用数组,而[会成为一个问题。 - mario
@Bhushan 不,前后的文本将会改变。 - kabuto178
5个回答

8
您正在定义$start和$end为数组,但是将其用作普通变量。尝试更改您的代码如下:
$start = '\[';
$end  = '\]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);

你在正则表达式模式中使用i修饰符来忽略大小写的是哪个字符? - undefined

1

怎么样?

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

应该在文本后面得到普通文本 [测试]

编辑

演示Fiddle 在这里


这是一个空输出。 - kabuto178

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

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

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接