使用str_replace编辑链接时出现问题


Trouble editing a link with str_replace

理想情况下,我希望使用php脚本作为每个页面上的include。

我有链接:http://www.facebook.com/sharer.php?u=http://123.456.789.101/~user/file.php

我想让它看起来像这样:http://www.facebook.com/sharer.php?u=http://MyUrl.com/file.php

本质上,我想用"MyUrl.com"取代"123.456.789.101/~user"

我需要更改多个链接。此外,每个页面的文件名"file.php"部分都会发生变化。我不知道确切的页面名称是什么。

我试过了,但不起作用。如果我回显str_replace,它会给我正确的链接,但我无法获得新的链接来替换页面中的旧链接。

<?php
$string = 'http://www.facebook.com/sharer.php?u=http://123.456.789.101/~user';
$pattern = '123.456.789.101/~user';
$replacement = 'MyUrl.com';
str_replace($pattern, $replacement, $string);
?>

非常感谢。

您需要设置新字符串。str_replace返回新字符串,它自己不设置。

$string = str_replace($pattern, $replacement, $string);

如果需要替换多个IP,则应考虑使用正则表达式。

试试这个

<?php
$string = 'http://www.facebook.com/sharer.php?u=http://123.456.789.101/~user';
$pattern = '123.456.789.101/~user';
$replacement = 'MyUrl.com';
$newString = str_replace($pattern, $replacement, $string);
echo $newString;
?>

在html中替换使用:

<a href="<?php echo $newString ?>>Anchor Text Here</a>