3

I've checked other answers but can't seem to do the following. Please help someone :)

I want to remove everything in between and including specific html comments

HTML:

Some HTML that must stay
<!-- START IF USER_ID -->
some html that must go
<!-- END IF USER_ID -->
Some more HTML that's gotta stay
<!-- START IF USER_ID -->
this also needs to go
<!-- END IF USER_ID -->

So everything in between <!-- START IF USER_ID --> and <!-- END IF USER_ID --> and the comments itself needs to go

My preg_replace pattern (which is obviously wrong):

"/<!-- START IF USER_ID -->.*?<!-- END IF USER_ID -->/"

Result should be

Some HTML that must stay
Some more HTML that's gotta stay

Thanks for checking and for the answers in advance :)

2

2 Answers 2

8

Thanks @mlwacosmos - Using the link you provided.

Achieved with:

$startPoint = '<!-- START IF USER_ID -->';
$endPoint = '<!-- END IF USER_ID -->';
$result = preg_replace('#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#siU', '', $html);
Sign up to request clarification or add additional context in comments.

2 Comments

How to do this but stop at the first $endpoint ? If you have xxx $start yyy $end zzz $end. I dont wanna delete the zzz because there is an enpoint before.
Thanks @neoteknic never realised this. Answer modified to include non-greedy modifier U which stops at the first one then continues onwards.
3

That regex looks fine. Use an m modifier to make the dot match newlines:

"/<!-- START IF USER_ID -->.*?<!-- END IF USER_ID -->/m"

Alternatively, you could use [\s\S] as a substitute:

"/<!-- START IF USER_ID -->[\s\S]*?<!-- END IF USER_ID -->/"

Comments

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.