Dev Utkarsh
Dev Utkarsh

Reputation: 1496

Rewrite a URL using preg_replace function

I have a url say like http://www.something.com/folder_path/contacts.php/ ( starting with http:// and ending with .php/ ). Please make sure about the slash(/) at the end of the URL.
Now I want to rewrite the URL by replacing the last element of URL i.e. /contacts.php/ to /index.php/ by matching it using regular expression.

Example code -

$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);

The result would be http://www.something.com/folder_path/index.php/

also the path could be longer..all I need to replace is the last part of the URL. Thanks.

Upvotes: 0

Views: 415

Answers (2)

Kamehameha
Kamehameha

Reputation: 5473

This can be done without regular expressions as well, using implode and explode. This should work-

$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/

Upvotes: 2

Manolo
Manolo

Reputation: 26410

This regex: $regex = "#[^/.*](\.....?)/$#"; is not matching contact.php. You should use:

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

This is matching any character except / + .php + / (optional) + END Of STRING

Upvotes: 1

Related Questions