Jump to content

Remove only a tag and all its contents


Parhs

Recommended Posts

Hello i am trying to remove a custom tag from the file but it doesnt work...

example

jfsajdfjsdlfdsa<if test=0>word</if>fejjkfewkfjewkfjkewjfk

should remove all the <if test=0>word</if>

i tried many things..This for example scr*s the output.It prints nothing...

echo preg_replace("/<if test=0>(.)*<\/if>/m","","<if test=0>pahoulo</if> <if test=1>pahoulo</if>");

 

Please help..

Link to comment
Share on other sites

/<if.*?if>/

 

edit:

 

Oh my bad.  I guess I read that wrong or maybe you could have been clearer or both.  Didn't notice you wanted to differentiate test=0 from test=1

 

Problem with your regex is that your * quantifier is being greedy and not stopping until the last </if>.  You need to tell it to not be greedy and stop gobbling up stuff when it reaches first match.  You do that by following it with a question mark ?.  Also, you do not need parenthesis around the dot, since it's only one character and you don't need to capture it.

 

/<if test=0>.*?<\/if>/m

Link to comment
Share on other sites

Thank you for the reply.That works.

But i need some further help..

I want to replace all the tags <if test=0>content</if>  with nothing.That means i want to erase them.

If <if test=1>content</if>  then replace that with content.

 

Your regex works fine but if there are nested tags it becomes a mess.

<if test=1>pasok

<if test=0>b</if>

<if test=1>a</if>

s</if>

 

So the only solution i think is to replace the most inner tags first and repeat the preg_replace.

But i cant find any good regex.

 

echo preg_replace("/<if test=0>(.)*?(?!<if)(.)*?<\/if>/s","",$pap,1);

 

this for example wouldnt work because for example <if test=0>b</if> wouldnt match because after that there is an <if test=1>a</if>

any help apreciated

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.