Reputation: 531
I'm trying to write a function in php where I want to replace all occurences of "www." with "http://www.".
$text = preg_replace("www\.", "http://www.", $data);
I've tried using this code but I do not want the string "http://www." to be turned into "http://http://www.".
Any suggestions?
Upvotes: 1
Views: 145
Reputation: 9650
Add the ^
anchor to you regex:
$text = preg_replace("/^www\./", "http://www.", $data);
^ -- this one
NB: mind the regex delimiters (/.../
) in the pattern parameter.
This start of line anchorhelps to ensure the www.
string to be replaced is at the beginning of the $data
string. It will prevent any undesired substitutions in the middle of a string like this: redirector.com/?www.stackoverflow.com
Upvotes: 3
Reputation: 339
Try this simplified code
i.e $url='www.xyz.com';
function urlModified($patterns, $replace, $url)
{
$patterns = array ('http://www.');
$replace = array ('/^www\./');
preg_replace($patterns, $replace, $url);
return $url;
}
Upvotes: 0
Reputation: 8606
Try this. This will check for not only HTTP, but also other protocols like HTTPS, FTP etc.
function addPrefix($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
echo addPrefix("http://ww.google.com");
Upvotes: 0
Reputation: 627082
You can achieve that with a negative lookbehind:
'~(?<!://)www\.~'
See the regex demo
The (?<!://)
lookbehind will fail a match if www.
is preceded with ://
thus avoiding the match in http://www.
and https://www.
.
If you really want to avoid matching strings that have http://
only, add http
or \bhttp
before the :
and use '~(?<!http://)www\.~'
Upvotes: 1