2011-01-19 24 views
1

有一些網址,例如11162_sport.html11451_sport.html11245_sport.html231sport.html, 我要當像XXXXX_sport.html的URL,然後取代他們進入11162_football.html11451_football.html11245_football.html231sport.html沒有變化。PHP的替代問題

如何替換它們,$newurl = preg_replace("_sport.html","_football.html",$url)?謝謝。

回答

3

只要做$newurl = str_replace("_sport.html", "_football.html", $url);
這比做一個preg_replace()和更多的accurant更快。

參見the manual on str_replace

1

您可以使用str_replace進行如此簡單的替換。

1

如果必須是正則表達式,做到:

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

str_replace()將不定取代sport.html所有 OCCURENCES而與最終的線的標記($)正則表達式將只更換URL末尾的模式。

該點需要轉義,因爲它會匹配任何字符(除了換行符)。