简体   繁体   English

使用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.

This is the PHP I've tried and generally it works:这是我尝试过的 PHP,通常它有效:

preg_replace('#\/\/CROPSTART[\s\S]+\/\/CROPEND#', '', $string);

However, when the string contains multiple "CROPEND" it crops everything from the CROPSTART to the last CROPEND.但是,当字符串包含多个“CROPEND”时,它会裁剪从 CROPSTART 到最后一个 CROPEND 的所有内容。 I would like it to only crop between the first CROPSTART and the first CROPEND.我希望它只在第一个 CROPSTART 和第一个CROPEND 之间进行裁剪。

Anyone know how to do this?有人知道怎么做吗?

Thanks Wonko谢谢旺科

However, when the string contains multiple "CROPEND" it crops everything from the CROPSTART to the last CROPEND.但是,当字符串包含多个“CROPEND”时,它会裁剪从 CROPSTART 到最后一个 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.这是因为您的+运算符是贪婪的 - 它不会在CROPEND的第一个实例处CROPEND并继续直到遇到最后一个实例。

You can use a non-greedy version of the + operator simply by appending a ?您可以使用的非贪婪版本+简单地通过附加操作? after it:之后:

preg_replace('/CROPSTART[\s\S]+?CROPEND/', '', $string);

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

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