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 以外的任何字符或更多次,最后我们使用结束]