Steve Steve - 1 month ago 19
PHP Question

PHP regular expression help

I am using preg_replace to strip out

<p>
tags and
<li>
tags and making them carriage returns. I have some
<a
> tags in my string, and I want to strip those out, but keep the href attribute. For instance, if I have:
<a href = "http://www.example.com">Click Here</a>
, what I want is:
http://www.example.com
Click Here

Here is what I have so far

$text .= preg_replace(array("/<p[^>]*>/iU","/<\/p[^>]*>/iU","/<ul[^>]*>/iU","/<\/ul[^>]*>/iU","/<li[^>]*>/iU","/<\/li[^>]*>/iU"), array("","\r\n\r\n","","\r\n\r\n","","\r\n"), $content);


Thanks

Answer

If I were you I would use SimpleHTMLDom. Here's a usage example from the docs:

// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; 
// Output: <div id="hello">foo</div><div id="world" class="bar">World</div>