繁体   English   中英

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

[英]PHP preg_replace text between two strings

我有一个字符串,其格式类似于下面的$ 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表达式,因此被困在这里。 任何帮助,将不胜感激。

注意:我尝试了drew010bsdnoobz提供的两个代码(感谢代码和说明),但仍然无法正常工作。 问题是我没有正确捕获$ 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字符,似乎也包括换行符或回车符,这可能是阻止下面提交的正则表达式对我不起作用的原因。

$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.

注意:输入字符串中同时包含单引号和双引号。 本示例将输入字符串括在单引号中,并对字符串中的任何单引号进行转义。

这也是一种有效的模式:

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

它将匹配您所拥有的格式,或者仅匹配[quote]Text...[/quote]

分解:

\\[quote[^\\]]*\\]表示匹配文本[quote ] 外的任何字符0次或更多次

\\]匹配闭合]在开口的端部[quote]标签。

.*? 匹配任何字符0次或更多次。 ? 在这种情况下,使该匹配不愉快(这意味着,当它首先匹配模式的下一部分而不是最后匹配模式时,它将停止。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM