Reputation: 612
How to change a href value if a certain string is found
$string ='<a href="http://facebook.com/feelingblue">Facebook</a>'
if facebook is found on the href, replace to just facebook.com
Upvotes: 1
Views: 522
Reputation: 2167
You String is :-
$str ='<a href="http://facebook.com/feelingblue">Facebook</a>';
You may extract the href value by doing this :-
preg_match_all('~<a(.*?)href="([^"]+)"(.*?)>~', $str, $matches);
Removing http://
$url = str_replace ('http://', '', $matches[2]);
Remove rest of the things after .com
$url = preg_replace ('/(\.com).*/','$1',$url);
Desired output would be
facebook.com
Upvotes: 0
Reputation: 1450
Try this,
$string ='<a href="http://facebook.com/feelingblue">Facebook</a>';
if (strpos($string, 'facebook') !== false) {
$facebookUrl = "http://www.facebook.com";
$regEx = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$newUrl = preg_replace($regEx,$facebookUrl,$string);
}
echo $newUrl;
I hope this helps.
Upvotes: 0
Reputation: 5501
I am assuming that you fetching these values from DB
$url = 'http://facebook.com/feelingblue'; // this is the url you are getting
if (strpos($url , 'facebook') !== false) {
$url = "https://facebook.com";
}
$string ='<a href="'.$url.'">Facebook</a>'
for more information
Upvotes: 0
Reputation: 8214
Use RegExp, if you are searching from the whole document.
preg_replace_callback('(<a href=")([^"]+)(">([^<]+)</a>)', function($match){
return $match[1] . "//example.com" . $match[3];
}, $html);
If you just want Facebook, you can add a check if($match[4] === "Facebook")
and/or if($match[2] === "http://facebook.com/feelingblue")
Upvotes: 0
Reputation: 1380
Use this code,
$string ='<a href="http://facebook.com/feelingblue">Facebook</a>';
echo preg_replace('#http://facebook.com/([^"]+)#is', 'http://www.facebook.com', $string );
Thanks Amit
Upvotes: 3