2

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);
6
  • you mean you need help with third? try escaping ampersand at &sub with \&sub Commented Feb 8, 2014 at 17:44
  • Remove the / right before &sub probably. Also, do the more specific replace first, the less specific one later. If that does not help, please specify input & desired output. Also note, that with proper error reporting, PHP would already have told you what was wrong with it. Commented Feb 8, 2014 at 17:44
  • Escape / as \/ like Wrikken mentioned Commented Feb 8, 2014 at 17:47
  • I get this index/test&sub=text Commented Feb 8, 2014 at 17:48
  • Can you give us the $html? Commented Feb 8, 2014 at 17:54

1 Answer 1

2

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

Comments

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.