Skip to content Skip to sidebar Skip to footer

Replace Href With A Different Value

I have some PHP code which grabs a website's HTML code, then echos it to the screen. I'm looking for a way to scan the HTML, and then replace all href values with another value. Fo

Solution 1:

You can use preg_replace() to replace the searched term in the string like this:

<?php
// example page contents
$pageContents = '<a href="http://somepage.com/somepage">Click me</a>Some example text.
<div>Example div <a href="http://anotherDomain.com/somepage2">Another link</a>.</div>';

//  ------ the Search pattern explanation -------
// (http:\/\/)? means that the http:// may or may not exist
// ([\w]+) the parentheses () will remember the expression inside
// the \s? means there may or may not be a space character there

//  ------ the Replace pattern explanation -------
// replace the matched expression with the provided replacement
// the $2 is the second parenthesized expression () from the search pattern
$html = preg_replace('/<a href="(http:\/\/)?[\w.]+\/([\w]+)"\s?>/', '<a href="http://mywebsite.com/$2">' ,$pageContents);

echo $html;
?>

which outputs:

Click meSome example text.

Example div Another link.

Post a Comment for "Replace Href With A Different Value"