views:

60

answers:

5

Hello, I'm new to regular expressions, but I'm trying to learn about it. I want to remove the tag of a html text, and let only the inner text. Something like that:

Original: Lorem ipsum <a href="http://www.google.es"&gt;Google&lt;/a&gt; Lorem ipsum <a href="http://www.bing.com"&gt;Bing&lt;/a&gt;
Result:  Lorem ipsum Google Lorem ipsum Bing

I'm using this code:

$patterns = array( "/(<a href=\"[a-z0-9.:_\-\/]{1,}\">)/i", "/<\/a>/i");
$replacements = array("", "");

$text = 'Lorem ipsum <a href="http://www.google.es"&gt;Google&lt;/a&gt; Lorem ipsum <a href="http://www.bing.com"&gt;Bing&lt;/a&gt;';
$text = preg_replace($patterns,$replacements,$text);

It works, but I don't know if this code is the more efficient or the more readable.

Can I improve the code in some way?

+7  A: 

In your case, PHP's strip_tags() should do exactly what you need without regular expressions. If you want to strip only a specific tag (something strip_tags() can't do by default), there is a function in the User Contributed Notes.

In general, regexes are not suitable for parsing HTML. It's better to use a DOM parser like Simple HTML DOM or one of PHP's built-in parsers.

Pekka
+5  A: 

Don't use regular expressions, use a DOM parser instead.

You
that should read *Don't use regular expressions* **for parsing (x)HTML**. It's not like they are totally useless ;)
Gordon
+2  A: 

If your content only contains anchor tags, then strip_tags is probably easier to use.

Your preg_replace won't replace if there are spurious spaces between a and href, or if there are any other attributes in the tag.

Mark Baker
A: 

You can't parse [X]HTML with regex.

mizipzor
Well, you can. It's just not a good idea to.
Pekka
Actually, you can't. (X)HTML is not a regular language, and as such can't be parsed by regular expressions.
You
+1  A: 

In this case, using regex is not a good idea. Having said that:

<?php
    $text = 'Lorem ipsum <a href="http://www.google.es"&gt;Google&lt;/a&gt; Lorem ipsum <a href="http://www.bing.com"&gt;Bing&lt;/a&gt;';
    $text = preg_replace(
        '@\\<a\\b[^\\>]*\\>(.*?)\\<\\/a\\b[^\\>]*\\>@',
        '\\1',
        $text
    );
    echo $text;
    // Lorem ipsum Google Lorem ipsum Bing
?>

This is a very trivial regex, its not bullet proof.

Salman A