使用preg_replace函数重写URL

时间:2014-02-01 21:00:31

标签: php regex

我有一个网址,如http://www.something.com/folder_path/contacts.php/(以http://开头,以.php /结尾)。请确保URL末尾的斜杠(/) 现在我想通过将URL的最后一个元素(即/contacts.php/替换为/index.php/)通过使用正则表达式匹配来重写URL。

示例代码 -

$url = "http://www.something.com/folder_path/contacts.php/";
$new_element = "index.php";

$regex = "#[^/.*](\.....?)/$#"; // what would be the regular expression 

$new = preg_replace($regex,$new_element, $url);

结果将是http://www.something.com/folder_path/index.php/

路径也可能更长。我需要替换的是URL的最后一部分。 感谢。

2 个答案:

答案 0 :(得分:2)

这可以在没有正则表达式的情况下完成,使用implode和explode。这应该有效 -

$url = "http://www.something.com/folder_path/contacts.php/";
$arr = explode("/",$url);
$new_element = "index.php";
$arr[count($arr) - 2] = $new_element;
echo implode("/",$arr);
// Prints - http://www.something.com/folder_path/index.php/

答案 1 :(得分:1)

此正则表达式:$regex = "#[^/.*](\.....?)/$#";contact.php不匹配。 你应该使用:

$regex = "#[^\/]+\.php\/?$#";

此匹配除/ + .php + /(可选)+ STRING结束

之外的任何字符