10

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:

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

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.

Anyone know how to do this?

Thanks Wonko

Wonko the Sane
  • 754
  • 3
  • 14
  • 31
  • maybe this can help: http://stackoverflow.com/questions/1899158/php-preg-replace-non-greedy-trouble – mmgross May 23 '15 at 01:08
  • possible duplicate of [How to get the shortest rather than longest possible regex match with preg\_match()](http://stackoverflow.com/q/5897478) – mario May 23 '15 at 01:18
  • Yes, looks like a dupe to me, guilty as charged. That said, the answer provided here was succinct and clear to understand. – Wonko the Sane May 23 '15 at 01:30

1 Answers1

24

However, when the string contains multiple "CROPEND" it crops everything from the CROPSTART to the last 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);
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • How would it work if I have "CROPSTART FirstWord CROPEND only this CROPSTART SecWord CROPEND" and I want to get " only this "? – Tom Senner Aug 16 '18 at 07:14