开发者

help me understand PHP's preg_replace

开发者 https://www.devze.com 2023-02-18 07:41 出处:网络
I have this link: http://mysite/myfolder/it/my-keywords.html and want to replace /it/ with /es/ (2 letter cou开发者_高级运维ntry codes)

I have this link: http://mysite/myfolder/it/my-keywords.html and want to replace /it/ with /es/ (2 letter cou开发者_高级运维ntry codes)

I could explode() with "/" delimiter but would like to understand if preg_replace would be better.

tried:

preg_replace("/\/([a-z]{2})/\/", $link, $country);

EDIT answer:

preg_replace("/\/[a-z]{2}\//", "/$country/", $link);


preg_replace is like a swiss army knife. preg rather than ereg means it uses perl compatible regular expressions. It matches first param (regex), replaces with second param (string) in third param (string).

Regular expressions are optimized for efficiency by using search tree cutoff techniques etc... so are generally efficient alternative method.

This should do what you want.

preg_replace("/\/it\//","/es/","http://mysite/myfolder/it/my-keywords.html") 


preg_replace is useful if you only know a part of string that you want to match, but others parts are variable. In your case the /it/ folder is already unique enough so that a static replacement would work. Use str_replace instead:

$url = str_replace("/it/", "/es/", $url);
0

精彩评论

暂无评论...
验证码 换一张
取 消