Php 将www.anylinks.com或anylinks.com替换为http://www.anylinks.com 在html内容中

Php 将www.anylinks.com或anylinks.com替换为http://www.anylinks.com 在html内容中,php,preg-replace,Php,Preg Replace,我需要有关替换格式“”的链接的帮助 例:从 $output_string = 'fix me <a href="www.link.com">link</a> or fix me <a href="link.com">link</a> and fix me too <a href="http://link.com">link</a> and replace me with <a href="http://www.

我需要有关替换格式“”的链接的帮助

例:从

    $output_string = 'fix me <a href="www.link.com">link</a> or fix me <a href="link.com">link</a> and fix me too <a href="http://link.com">link</a> and replace me with <a href="http://www.link.com>link</a>';
$output_string='fix me或fix me and fix me too并将我替换为';

$output_string='fix me或fix me and fix me too并将我替换为';

您可能不想重写
http://anylinks.com
http://www.anylinks.com
因为某些域不使用
www
前缀

$output_string = preg_replace('/(href=\")(http:\/\/)?/i', '$1http://', $output_string);
这个regexp将在字符串中找到href标记,并添加http://如果它还没有。搜索“www”更好,因为URL可能不以www开头。它不区分大小写。

您可以使用该函数来实现这一点

$str = 'fix me <a href="www.link.com">link</a> or fix me <a href="link.com">link</a> and fix me too <a href="http://link.com">link</a> and replace me with <a href="http://www.link.com>link</a>';
echo str_replace('www.www', 'www', str_replace('http://www.http://', 'http://www.', str_replace('a href="', 'a href="http://www.', $str)));
$str='fix me或fix me and fix me too并将我替换为';
echo str_replace('www.www','www',str_replace('http://www.http://', 'http://www.,str_replace('a href=“”,'a href='http://www.“,$str”);
这将输出

'fix me <a href="http://www.link.com">link</a> or fix me <a href="http://www.link.com">link</a> and fix me too <a href="http://www.link.com">link</a> and replace me with <a href="http://www.link.com>link</a>'
“修复我或修复我,也修复我,并用替换我”

我认为更好的方法是该函数的不区分大小写版本-。我认为更好的方法将是正则表达式,无论如何,您需要将www.www=>www的替换更改为www.www.=>www.因为如果网站以http://www开头,并且www是名称的一部分(这里的示例)http://wwwooooo.com就会失败。我碰巧遇到一个网站,其www版本完全是另一个网站。我只想说www.example.com!=当然,这同样适用于协议。这就是我在@Sharky上得到的,还有一些站点不会有
www
活动,因为它们会立即指向SSL,而SSL可能只有在没有子域的情况下才有效。
'fix me <a href="http://www.link.com">link</a> or fix me <a href="http://www.link.com">link</a> and fix me too <a href="http://www.link.com">link</a> and replace me with <a href="http://www.link.com>link</a>'