简体   繁体   English

如何在PHP中使用正则表达式删除特定字符之间的字符串?

[英]How to remove a string between the specific characters using regular expression in PHP?

I have string like below, 我有下面的字符串,

$string = "test coontevt [gallery include=\"12,24\"] first [gallery include=\"12,24\"] second";

i need to remove the string starts with [gallery to first ocuurance of it's ] . 我需要删除该字符串开头[gallery先ocuurance的是]

i already use this one, 我已经用过了

$string12 = preg_replace('/[gallery.+?)+(/])/i', '', $string);

but i get empty string only. 但我只得到空字符串。

Finally i want result for the above string is, 最后我想要上述字符串的结果是,

$string ="test coontevt first second".

How can i do this using regular expression?. 如何使用正则表达式执行此操作?

plz help me? 请帮我吗?

The character [ is a regex meta-character. 字符[是正则表达式元字符。 TO match a literal [ you need to escape it. 要匹配文字[您需要对其进行转义。

$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);

or 要么

$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);

You need to escape the square brackets 您需要转义方括号

$string12 = preg_replace('/\[gallery.+?\]/i', '', $string);

The round brackets are unnecessary so I removed them, also the quantifier between those brackets and the forward slash before the last square bracket. 圆括号是不必要的,因此我删除了它们,也删除了这些括号之间的量词以及最后一个方括号之前的正斜杠。

To avoid multiple space in the result, I would match also the surrounding spaces and replace with 1 space. 为了避免结果中出现多个空格,我还要匹配周围的空格并替换为1个空格。

\\s+\\[gallery.+?\\]\\s+ and replace with one space \\s+\\[gallery.+?\\]\\s+并替换为一个空格

$string12 = preg_replace('/\s+\[gallery.+?\]\s+/i', ' ', $string);

See this expression here online on Regexr 在Regexr上在线查看此表达式

Try it like this: 像这样尝试:

$string12 = preg_replace('/\[gallery[^\]]+\]/i', '', $string);

[^\\]]+ means that there can be one or more character that is not ] . [^\\]]+表示可以有一个或多个不是]字符。 And there is no need for any ( and ) if you don't want to use the backreferences. 而且,如果您不想使用反向引用,则不需要任何()

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

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