Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

replacing a string with preg_replace

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?

Upvotes: 0

Views: 1430

Answers (3)

Jon
Jon

Reputation: 437386

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_quote like this:

$url = 'http://Example.com/'
$pattern = preg_quote($url.'{word}/{word}/{word}', '/');
$pattern = str_replace($pattern, '{word}', '(\w+)');
$pattern = "/$pattern/i";
$replacement = $url.'$2/$3';
$appUrl= preg_replace($pattern, $replacement, $appUrl);

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 . in Example.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 $2 inside 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.

Upvotes: 0

Adam
Adam

Reputation: 5141

You need to escape your forward-slashes within the pattern, or use different pattern delimiters.

$pattern = '/http:\/\/Example\.com\/(\w+)\/(\w+)\/(\w+)/i';               

$pattern = '#http://Example\.com/(\w+)/(\w+)/(\w+)#i';               

Upvotes: 3

Nadh
Nadh

Reputation: 7243

Escape the slashes like this:

$pattern = '/http:\/\/Example.com\/(\w+)\/(\w+)\/(\w+)/i';               
$replacement="http://Example.com/$2/$3";
$appUrl= preg_replace($pattern, $replacement, $appUrl);

Upvotes: 0

Related Questions