PHP preg_replace两个字符串之间的文本

时间:2012-05-31 05:03:07

标签: php regex

我有一个字符串,其格式与$ string相似(从论坛帖子中提取)。

$string = "[quote=\"abc123\":27zslwh3]I don't agree with most of the statements made here.[/quote:27zslwh3] I don't think that is very nice of you.";
$pattern = "/\[quote\=.\*\[\/quote.*\]/";
$replace = "";

$updated_text = preg_replace($pattern,$replace,$string);
echo $updated_text;

我正在尝试使用preg_replace删除开始和结束[quote]标签之间的所有文本,并回显剩下的字符串:“我认为你不是很好。”只(从上面的$ string)。

我用于正则表达式的模式应该查找开始[quote]标记的开头,然后搜索直到它找到标记的结束[quote]标记和最终]。

上面似乎没有正常工作,我不太熟悉reg表达式,所以我被困在这里。任何帮助将不胜感激。

即可。

注意:我尝试了 drew010 bsdnoobz 提供的两个代码(感谢代码和解释) 它仍然无法正常工作。问题是我没有正确捕获$ string文本。它应该是:

$string = '[quote="abc123":27zslwh3]I dont agree with most of the statements made here.

abc123[/quote:27zslwh3]
I dont think that is very nice of you.';

双引号有html字符,看起来也是新行或回车字符,这可能是阻止下面提交的正则表达式对我不起作用的原因。

2 个答案:

答案 0 :(得分:2)

$string = '[quote="abc123":27zslwh3]I don\'t agree with most of the statements made here.[/quote:27zslwh3] I don\'t think that is very nice of you.';
echo preg_replace('/\[quote.+?\].+?\[\/quote.+?\]/is', '',$string);
// will print: I don't think that is very nice of you.

注意:输入字符串中有单引号和双引号。此示例使用单引号包装输入字符串,并转义字符串中的任何单引号。

答案 1 :(得分:2)

这是一个有效的模式:

$pattern = '/\[quote[^\]]*\].*?\[\/quote[^\]]*\]/is';

它会匹配您拥有的格式,或者只是简单地引用[quote]Text...[/quote]

等引号

要打破它:

\[quote[^\]]*\]匹配文字[quote和任何字符 ] 0次或更多次

\]与开放]标记末尾的结束[quote]匹配。

.*?匹配任何字符0次或更多次。此上下文中的?使得此匹配不合适(意味着当它首先匹配模式的下一部分而不是最后一部分时将停止。

\[\/quote[^\]]*\]然后匹配[/quote和任何字符 ] 0次或更多次,最后我们使用结束]

相关问题