0

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.

2 Answers 2

2

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/
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks . I already did this. But I wanted to do it by regex specifically.
1

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

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

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

7 Comments

Yeah..thanks a lot..it worked. :D Can you explain me the Regular expression before .php please?
[^\/]+ means any character except / . / must be escaped (\/). [^a] is any character except a or [^a-z] is any character except a, b, c, ..., z or [^abc] is any character except a, b, c ...
Thanks @manolo though I forgot to mention that extension may vary in original URL so i extended your answer to $reg = "#[^\/]+\..{3,4}\/$#";
@DevUtkarsh Are you sure that works? Check this out... or this. I mean, it's replacing the slash at the end.
@jerry - my target was to append the new element in original URL. It doesn't matters what the appended URL results in. I only had to take care of slash(/) in original URL because I was writing the regex for it .. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.