Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在两个限制之间替换文本_Php_Regex - Fatal编程技术网

Php 在两个限制之间替换文本

Php 在两个限制之间替换文本,php,regex,Php,Regex,我一直在尝试将两个符号之间的文本替换为preg_replace,但遗憾的是,仍然没有完全正确,因为我得到了一个空字符串的空输出,这就是我到目前为止得到的结果 $start = '["'; $end = '"]'; $msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']); 因此,我正在寻找的一个示例输出是: normal text [everythingheregone] afte

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

$start = '["';
$end   = '"]';
$msg   = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);
因此,我正在寻找的一个示例输出是:

normal text [everythingheregone] after text 


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

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

$str  = "normal text [everythingheregone] after text";
$repl = "test";
$patt = "/\[([^\]]+)\]/"; 
$res  = preg_replace($patt, "[". $repl ."]", $str);
应在文本后生成
正常文本[测试]

编辑


小提琴演示

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

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

一些可能有用的功能

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


普通文本和后文本是否始终不变?
$start
$end
锚定必须是字符串,并且必须转义。您正在使用一个数组,
[
将是一个问题。@Bhushan否前后的文本将发生变化。这也会给出一个空白输出
<?php
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
?>
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];
    }