Is it possible to convert the first block a text to the second block of text using PHP? If so, how? Thanks
<div>
<p>Some text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
<p>More text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
</div>
<div>
<p>Some text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
<p>More text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
</div>
EDIT. Per Andy’s recommendation, looking at something like the following. Still struggling on the converting of links, but it looks like a good start.
libxml_use_internal_errors(true); //Temporarily disable errors resulting from improperly formed HTML
$doc = new DOMDocument();
$doc->loadHTML($array['message_text']);
$a = $doc->getElementsByTagName('a');
foreach ($a as $link)
{
//Where do I go from here?
}
$array['message_text'] = $doc->saveHTML();
libxml_use_internal_errors(false);
First off, your HTML is malformed, as
&needs to be encoded as its HTML entity&. Fixing this gives us:From here, you shouldn’t use a regex. It is incredibly brittle and not meant for parsing HTML. Instead, you can use PHP’s
DOMDocumentclass to parse the HTML, extract the<a>tags, pull the information you want from them, create the new HTML elements, and insert them into the appropriate place.This prints: