使用preg_replace删除php中两个字符串之间的文本 [英] Deleting text between two strings in php using preg_replace
问题描述
我一直在尝试从两个标签之间的站点的字符串中删除一段文本.例如:
I've been trying to remove a section of text from a string the sites betweem two tags. For example:
This is CROPSTART not very CROPEND cool.
...应该变成这个...
...should become this...
This is cool.
这是我尝试过的PHP,通常可以正常工作:
This is the PHP I've tried and generally it works:
preg_replace('#\/\/CROPSTART[\s\S]+\/\/CROPEND#', '', $string);
但是,当字符串包含多个"CROPEND"时,它将裁剪从CROPSTART到最后一个CROPEND的所有内容.我希望它只在第一个CROPSTART和第一个 CROPEND之间裁剪.
However, when the string contains multiple "CROPEND" it crops everything from the CROPSTART to the last CROPEND. I would like it to only crop between the first CROPSTART and the first CROPEND.
有人知道该怎么做吗?
谢谢 元子
推荐答案
但是,当字符串包含多个"CROPEND"时,它将裁剪从CROPSTART到最后一个CROPEND的所有内容.
However, when the string contains multiple "CROPEND" it crops everything from the CROPSTART to the last CROPEND.
这是因为您的+
运算符是贪婪的-它不会在CROPEND
的第一个实例处停止并继续直到遇到最后一个实例.
This is because your +
operator is greedy - it won't stop at the first instance of CROPEND
and continue until it encounters the last instance.
只需在其后添加?
,即可使用+
运算符的非贪婪版本:
You can use a non-greedy version of the +
operator simply by appending a ?
after it:
preg_replace('/CROPSTART[\s\S]+?CROPEND/', '', $string);
这篇关于使用preg_replace删除php中两个字符串之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!