Speed up development with full-stack environments for every branch.

Learn More

Replace href values of html links using regular expressions [PHP and PCRE]

2325 Runs 14038 Views 7178 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php
/*
 * PHP PCRE - Replace href values of html links using regular expressions
 */

echo "<p>(Mouse over the links and see the url pointed)</p>";

$string = "<p>Please <a href='http://example.com'>click here</a> to go to <a href='http://example.com'>the site</a></p>";
$newurl = "http://myotherexample.com";
$pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newstring = preg_replace($pattern,$newurl,$string);
echo $string;
echo $newstring;
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).