替换字符串 preg_replace regex php 中的 url
I need to replace urls in my content with another url prefix:
i.e. if the current url is <a href="http://myoldurl.com">link</a>
and I want to change it to:<a href="http://myurl.com/create/?url=http://myoldurl.com">link</a>
how can replace my links using preg_replace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
免责声明:
使用 (X)HTML 时最好使用专用解析器。当然,某些包含标记的文件可能会导致此正则表达式解决方案失败。放置在注释、CDATA 部分、脚本、样式和/或属性值内的邪恶边缘情况字符串可能会出错。 (尽管这些应该非常罕见。)
也就是说......
这里的许多人会告诉您永远不要在 HTML 中使用正则表达式。然而,这个问题涉及一个非常具体的目标字符串,精心设计的正则表达式解决方案可以很好地完成手头的这一一次性任务。我将这样做:
仅当位于
A
链接标记的HREF
属性内时(值用单引号或双引号括起来),才会替换目标 URL 。它还会删除可能附加到旧目标 URL 的任何路径/查询/片段。它允许任意数量的其他标记属性出现在HREF
属性之前。Disclaimer:
It is always best to use a dedicated parser when working with (X)HTML. There are certainly files containing markup that can cause this regex solution to fail. Evil edge case strings placed inside comments, CDATA sections, scripts, styles and/or attribute values can trip it up. (Although these should be very rare.)
That said...
Many here will tell you to NEVER use regex with HTML. However, this question involves a very specific target string, and a carefully crafted regex solution can work pretty well for this one-shot task at hand. Here is how I would do it:
This will replace the target URL only when inside the
HREF
attribute ofA
link tags (with the value wrapped in either single or double quotes). It will also strip any path/query/fragment that may be appended to the old target URLs. It allows any number of other tag attributes to appear before theHREF
attribute.将用
http://myurl.com/create/?url=http:// 替换
:$string
中每个链接中的每个http://myoldurl.com
/myoldurl.comWill replace every
http://myoldurl.com
in every link in$string
byhttp://myurl.com/create/?url=http://myoldurl.com
: