Replacing element inside another element

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
jrundruud
Forum Newbie
Posts: 1
Joined: Thu Apr 17, 2008 1:48 pm

Replacing element inside another element

Post by jrundruud »

Hi there!
I've been doing PHP for a few months now, and I feel I'm getting used to it. However, the first time I saw complex regex-examples, I wondered what that line with random signs, letters and numbers had to do with PHP :)

Now, I have only encountered one big regex-related challenge, which has been a source for headache the last week

I want this regex to do the following:
Select the <br>-tags between <pre>-tags in a string

Code: Select all

<br>foo<pre>foobar[color=#FF4000]<br>[/color]barfoo[color=#FF4000]<br>[/color]</pre>bar
and replace it with nothing. The result of the example above shoult therefore look like this:

Code: Select all

<br>foo<pre>foobarbarfoo</pre>bar
I've done many attempts to create a pattern like that, but I have given up. Could anyone please help me here?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Replacing element inside another element

Post by prometheuzz »

Try this:

Code: Select all

 
#!/usr/bin/php
<?php
    $text = "<br>foo<pre>foobar<br>barfoo<br></pre>bar";
    echo $text . "\n";
    echo preg_replace('/<br>[^<]*<br>/', '', $text) . "\n";
?>
 
Post Reply