-1

want to repalce /randomword/ (wildcard) with /page-1/ so url would be replaced as http://www.example.com/randomword/page-1/fixed/index?ok=as

$url="http://www.example.com/randomword/fixed/index?ok=as";


$url= preg_replace('//(.*?)/fixed', '/randomword/page-1/fixed', $url);

not working the / confuses me when i dont know when to escape it

(read PHP str_replace with wild card?)

5
  • Regex's need delimiters in PHP. php.net/manual/en/regexp.reference.delimiters.php Commented Jan 19, 2017 at 4:27
  • i read it but seems overly complicated with no examples Commented Jan 19, 2017 at 4:32
  • See examples here, php.net/manual/en/function.preg-replace.php. The first / is the opening delimiter the last / is the closing one. Everything inbetween is the regex. From the first link note: If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.... so ~/(.*?)/fixed~ i think would resolve your issue. You also might prefer any non / over (.*?). Commented Jan 19, 2017 at 4:33
  • If /fixed/ is constant you could just str_replace that by prepending the new dir on it. Commented Jan 19, 2017 at 4:43
  • Possible duplicate of What Delimiter to use for preg_replace in PHP (replace working outside of PHP but not inside) Commented Jan 19, 2017 at 5:11

1 Answer 1

1

There is no wild card for str_replace(); you want to use preg_replace() instead.

Try this:

$url= preg_replace('~/(.*?)/fixed~', '/randomword/page-1/fixed', $url);

In addition, here's a great tool to help you build regular expressions in different languages: http://txt2re.com/

Further reading:

Big thanks to @chris85 who supplied most of the information for this answer!

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.