user3274509
user3274509

Reputation: 25

PHP preg_replace url string

Ok, so I have a preg_replace statement to replace a url string. First and second variable working but I need help for second string sub ....

$html = str_replace('index.php','index',$html);
$html = preg_replace('/index\?cat=([a-z0-9]+)/i','index/$1',$html);
$html = preg_replace('/index\?cat=([a-z0-9]+)/&sub=([a-z0-9]+)/i','index/$1/$2',$html);

Upvotes: 2

Views: 1201

Answers (1)

Toto
Toto

Reputation: 91415

Assuming $html contains:

index.php?cat=123&sub=456

after the str_replace $html becomes:

index?cat=123&sub=456

after the first preg_replace:

index/123&sub=456

Then the second preg_replace doesn't match.

You'd better to modify the order of the preg_replace:

//$html  ->  index.php?cat=123&sub=456
$html = str_replace('index.php','index',$html);
//$html  ->  index?cat=123&sub=456
$html = preg_replace('/index\?cat=([a-z0-9]+)&sub=([a-z0-9]+)/i','index/$1/$2',$html);
//$html  ->  index/123/456
$html = preg_replace('/index\?cat=([a-z0-9]+)/i','index/$1',$html);
//$html  ->  index/123/456

Upvotes: 2

Related Questions