Jump to content

Simple regexp string replacement help


David Nelson

Recommended Posts

Hi,

 

I have a series of strings like this:

 

<1><2><a>Test1</a>

<1><2><a>Test2</a>

...

 

I want to be able to replace <a> and </a>, without affecting what is in between the two <a> tags. I only want this to happen when <1><2> are present before <a>

 

In other words, I can't just do str_replace on <a> and </a>, because it must match the pattern of <1> and <2> preceding the <a> tags.

 

I'm sure this is super simple, but I'm having issues figuring out exactly what to do.

 

Let me know if you need any clarification. :)

 

Thanks,

David

Link to comment
Share on other sites

You can use preg_replace():

 

$str = preg_replace('~<1><2><a>(.*?)</a>~i', '<1><2>$1', $str);

That removes the a tags. If you want to replace them with something, just add that around $1 in the replacement. If you like fancier regex patterns, you could also use a positive lookbehind:

 

$str = preg_replace('~(?<=<1><2>)<a>(.*?)</a>~i', '$1', $str);

Link to comment
Share on other sites

OFF-TOPIC:  What does (?<=) ???

 

 

That is a positive lookbehind assertion.. so the character that follow after the = is what is needed to be there prior to what comes next after the lookbehind in the pattern. The only drawback to lookbehind assertions is that you cannot have unknown quantity of characters.. so stuff like (?<=d+) will fail becuase of the + quantifier for example. Or rephrased, lookbehinds must know exactly what it needs to find.

 

The notations are as follows:

 

(?<=) Positive lookbehind: (?<=foo)bar matches bar only if foo comes right before it

(?<!) Negative Lookbehind: (?<!foo)bar matches bar only if foo doesn't come right before it

(?=) Positive lookahead foo(?=bar) matches foo only if bar comes right after it

(?!) Negative lookahead foo(?!bar) matches foo only if bar isn't right after it

 

What is important to note is that the text within assertions are not actually matched.. rather, regex seeks to see if those character are there (or not). So assertion content themselves never shows up in final matched results.

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.