php 匹配和替换

发布于 2024-09-27 10:49:18 字数 882 浏览 0 评论 0原文

我想用字符串的修改版本替换我在字符串中找到的每个链接,例如:

敏捷的棕色狐狸跳过了http://www.google.com/?v=abc http://www.google.com/?v=x_y-z< /a>
我将替换(并修改)其中的链接,使其变为:
http://www.google.com/ v/abchttp://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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瑾夏年华 2024-10-04 10:49:18

为此,请使用 preg_replace

$str = preg_replace('/\?v=([^ ]*)/', '/v/$1', $str);

这假设您希望匹配 ?v= 之后的所有内容并将其放在 /v/ 之后。如果情况并非如此,您就必须更具体地了解该模式是什么。

Use preg_replace for that:

$str = preg_replace('/\?v=([^ ]*)/', '/v/$1', $str);

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.

囚我心虐我身 2024-10-04 10:49:18

使用 g(全局)和 i(不区分大小写)标志应该将搜索扩展到所有内容。

$string = preg_replace('/\?v=([^\s]+)/gi','/v/$1', $string);

这假设您的网址后面有某种类型的空格。

using the g (global) and i (case insensitive) flags should extend the search to everything.

$string = preg_replace('/\?v=([^\s]+)/gi','/v/$1', $string);

This assumes that there is some type of whitespace after your url.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文