用另一个网址替换一个网址

时间:2020-03-06 14:34:12  来源:igfitidea点击:

在PHP中,将一个网址替换为字符串中的另一个网址,例如

New post on the site <a href="http://stackoverflow.com/xyz1">http://stackoverflow.com/xyz1</a></p>

变成:

New post on the site <a href="http://yahoo.com/abc1">http://yahoo.com/abc1</a></p>

必须像上面那样重复字符串。赞赏这很简单,但很努力!

解决方案

使用str_replace():

$text = str_replace('http://stackoverflow.com/xyz1', 'http://yahoo.com/abc1', $text);

这会将第一个URL替换为$ text中的第二个URL。

试试这个:

preg_replace('#(https?://)(www\.)?stackoverflow.com\b#', 'yahoo.com', $text);

如果要更改URL后面的路径,请添加另一个组并使用preg_replace_callabck。 PHP文档中的更多信息。

function replace_url($text, $newurl) {
    $text = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', $newurl, $text);
    return $text;
}

应该管用。
正则表达式从这里被盗。这会将字符串中的所有URL替换为新的URL。