cj333
cj333

Reputation: 2609

php replace problem

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.

Upvotes: 1

Views: 69

Answers (3)

Linus Kleen
Linus Kleen

Reputation: 34632

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).

Upvotes: 1

Samuel Herzog
Samuel Herzog

Reputation: 3611

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.

Upvotes: 3

Matěj Zábský
Matěj Zábský

Reputation: 17272

you can use str_replace for such simple replacement.

Upvotes: 1

Related Questions