我一直在尝试用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
您将$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);
应产生normal text [test] after text
编辑
Fiddle演示在这里
一些可能有助于的功能
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];
}
$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
我有一个regex方法。正则表达式为:'[.*?]
<?php
$string = 'normal text [everythingheregone] after text ';
$pattern = ''[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
?>