帮助我理解 PHP 的 preg_replace
我有这个链接: http://mysite/myfolder/it/my-keywords.html 并想要替换/it/ 和 /es/ (2 个字母的国家/地区代码)
我可以使用“/”分隔符 explode()
但想了解 preg_replace 是否会更好。
尝试过:
preg_replace("/\/([a-z]{2})/\/", $link, $country);
编辑 回答:
preg_replace("/\/[a-z]{2}\//", "/$country/", $link);
I have this link:
http://mysite/myfolder/it/my-keywords.html and want to replace /it/ with /es/ (2 letter country 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
preg_replace 就像一把瑞士军刀。 preg 而不是 ereg 意味着它使用 perl 兼容的正则表达式。它匹配第一个参数(正则表达式),用第三个参数(字符串)中的第二个参数(字符串)替换。
正则表达式通过使用搜索树截止技术等来优化效率......因此通常是有效的替代方法。
这应该做你想做的。
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/ 文件夹已经足够唯一,因此可以进行静态替换。使用
str_replace
代替: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: