11

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

3

1 Answer 1

25

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);
Sign up to request clarification or add additional context in comments.

1 Comment

How would it work if I have "CROPSTART FirstWord CROPEND only this CROPSTART SecWord CROPEND" and I want to get " only this "?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.