php 匹配和替换
我想用字符串的修改版本替换我在字符串中找到的每个链接,例如:
敏捷的棕色狐狸跳过了http://www.google.com/?v=abc 和 http://www.google.com/?v=x_y-z< /a>
我将替换(并修改)其中的链接,使其变为: http://www.google.com/ v/abc 和 http://www.google.com/v/x_y-z
我知道如何使用 preg_match_all($pattern, $text, $out, PREG_SET_ORDER); 查找所有链接 我可以使用 preg_split 等操作字符串 - 这是一次完成一个。
我正在寻找的结果是:
敏捷的棕色狐狸跳过了http://www.google.com/v/abc 和 http://www.google.com/v/=x_y-z
但是我怎样才能匹配和替换它们呢?任何帮助将不胜感激。
I want to replace every link I find within a string, with a modified version of the string, say for example:
The quick brown fox jumped over the http://www.google.com/?v=abc and http://www.google.com/?v=x_y-z
I would replace (and modify) the links in this so it becomes: http://www.google.com/v/abc and http://www.google.com/v/x_y-z
I know how to find all the links using preg_match_all($pattern, $text, $out, PREG_SET_ORDER);
and I can manipulate the strings using preg_split etc - This is done one at a time.
The outcome I'm looking for is:
The quick brown fox jumped over the http://www.google.com/v/abc and http://www.google.com/v/=x_y-z
However how could I match and replace all of them? Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,请使用
preg_replace
:这假设您希望匹配
?v=
之后的所有内容并将其放在/v/
之后。如果情况并非如此,您就必须更具体地了解该模式是什么。Use
preg_replace
for that:This assumes that you want to match everything after
?v=
and put it after the/v/
. If that's not the case, you'll have to be more specific about what the pattern is.使用 g(全局)和 i(不区分大小写)标志应该将搜索扩展到所有内容。
这假设您的网址后面有某种类型的空格。
using the g (global) and i (case insensitive) flags should extend the search to everything.
This assumes that there is some type of whitespace after your url.