1

there are some url, like 11162_sport.html, 11451_sport.html, 11245_sport.html or 231sport.html, I want when the url like XXXXX_sport.html then replace them into 11162_football.html, 11451_football.html, 11245_football.html, and 231sport.html has no change.

how to replace them, $newurl = preg_replace("_sport.html","_football.html",$url)? Thanks.

3 Answers 3

3

Simply do $newurl = str_replace("_sport.html", "_football.html", $url);
This is faster than doing a preg_replace() and more accurant.

see the manual on str_replace.

Sign up to request clarification or add additional context in comments.

Comments

1

you can use str_replace for such simple replacement.

Comments

1

If it must be regular expressions, do:

preg_replace('/_sport\.html$/', '_football.html', $url);

str_replace() would indeterminately replace all occurences of sport.html whereas a regular expression with an end-of-line marker ($) will only replace the pattern at the end of the URL.

The dot needs to be escaped because it would match any character (except new-lines).

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.