I have a URL like this:
http://Example.com/mobile-ds-cams/mobile-gg-cams/ddd-webcams
Example:
$pattern = '/http://Example.com/(\w+)/(\w+)/(\w+)/i';
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);
What I want to achieve is this
http://Example.com/mobile-gg-cams/ddd-webcams
I am trying to keep 2 “sub-URLs” instead of 3. but it doesn’t work..why?
It doesn’t work correctly because your expression contains characters with special meaning in a regex that have not been properly quoted.
To be 100% certain, use
preg_quotelike this:Otherwise, it’s simply too easy to get things wrong. For example, all of the other answers currently posted here get it wrong because they do not properly escape the
.inExample.com. You can test this yourself if you feed them a string like e.g.http://Example!com, where!can be any character you like.Additionally, you are using strings such as
$2inside a double-quoted string literal, which is not a good idea in PHP because IMHO it’s easy to get carried away. Better make that singly quoted and be safe.