I am trying to use some regular expressions to change out the titles in some links.
I have these links:
<a class="postlink" href="http://espn.go.com/">http://espn.go.com/</a>
That I want to change to:
<a class="postlink" href="http://espn.go.com/">ESPN: The Worldwide Leader In Sports</a>
I have the function created to grab the url title block, but I can’t figure out how to replace the url with the title.
Any suggestions?
$link = '<a class="postlink" href="http://espn.go.com/">http://espn.go.com/</a>';
$newTitle = 'ESPN: The Worldwide Leader In Sports';
$newLink = preg_replace('#(<a.*?>)[^>]*(</a>)#s', '${1}'.$newTitle.'${2}', $link);
Trying to use Regular Expressions for this would be very very unreliable.
$doc = new DOMDocument;
$doc->loadHTML( $html );
$xp = new DOMXPath( $doc );
foreach ( $xp->query( '//a[@class="postlink"]' ) as $link ) {
// Get title here and stuff...
$text = "SuperLink: " . $link->textContent;
$link->removeChild( $link->firstChild );
$link->appendChild( new DOMText( $text ) );
}
echo $doc->saveHTML();