替换字符串 preg_replace regex php 中的 url

发布于 2024-12-09 15:10:47 字数 214 浏览 1 评论 0原文

我需要将内容中的 url 替换为另一个 url 前缀: 即如果当前网址为 link 并且我想将其更改为: link 如何使用 preg_replace 替换我的链接?

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 技术交流群。

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

发布评论

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

评论(2

旧时浪漫 2024-12-16 15:10:47

免责声明:

使用 (X)HTML 时最好使用专用解析器。当然,某些包含标记的文件可能会导致此正则表达式解决方案失败。放置在注释、CDATA 部分、脚本、样式和/或属性值内的邪恶边缘情况字符串可能会出错。 (尽管这些应该非常罕见。)

也就是说......

这里的许多人会告诉您永远不要在 HTML 中使用正则表达式。然而,这个问题涉及一个非常具体的目标字符串,精心设计的正则表达式解决方案可以很好地完成手头的这一一次性任务。我将这样做:

$text = preg_replace('%
    # Match A element open tag up through specific HREF value.
    (                     # $1: Everything up to target HREF value.
      <A                  # Literal start of A element open tag.
      (?:                 # Zero or more attributes before HREF.
        \s+               # Whitespace required before each attribute.
        (?!HREF)          # Assert this attribute is not HREF.
        [\w\-.:]+         # Required attribute name.
        (?:               # Attribute value is optional.
          \s*=\s*         # Attrib value separated by =.
          (?:             # Group attrib value alternatives.
            "[^"]*"       # Either double quoted value,
          | \'[^\']*\'    # or single quoted value,
          | [\w\-.:]+     # or unquoted value.
          )               # End attrib value alternatives.
        )?                # Attribute value is optional.
      )*                  # Zero or more attributes before HREF.
      \s+                 # Whitespace required before HREF attribute.
      HREF                # HREF attribute name.
      \s*=\s*             # Value separated by =, optional whitespace.
    )                     # End $1: Everything up to target HREF value.
    ([\'"])               # $2: HREF attrib value opening quote.
    http://myoldurl\.com  # Target URL to be replaced.
    .*?                   # Any path/query/fragment on target URL.
    \2                    # HREF attrib value matching closing quote.
    %xi',
    '$1"http://myurl.com/create/?url=http://myoldurl.com"',
    $text);

仅当位于 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:

$text = preg_replace('%
    # Match A element open tag up through specific HREF value.
    (                     # $1: Everything up to target HREF value.
      <A                  # Literal start of A element open tag.
      (?:                 # Zero or more attributes before HREF.
        \s+               # Whitespace required before each attribute.
        (?!HREF)          # Assert this attribute is not HREF.
        [\w\-.:]+         # Required attribute name.
        (?:               # Attribute value is optional.
          \s*=\s*         # Attrib value separated by =.
          (?:             # Group attrib value alternatives.
            "[^"]*"       # Either double quoted value,
          | \'[^\']*\'    # or single quoted value,
          | [\w\-.:]+     # or unquoted value.
          )               # End attrib value alternatives.
        )?                # Attribute value is optional.
      )*                  # Zero or more attributes before HREF.
      \s+                 # Whitespace required before HREF attribute.
      HREF                # HREF attribute name.
      \s*=\s*             # Value separated by =, optional whitespace.
    )                     # End $1: Everything up to target HREF value.
    ([\'"])               # $2: HREF attrib value opening quote.
    http://myoldurl\.com  # Target URL to be replaced.
    .*?                   # Any path/query/fragment on target URL.
    \2                    # HREF attrib value matching closing quote.
    %xi',
    '$1"http://myurl.com/create/?url=http://myoldurl.com"',
    $text);

This will replace the target URL only when inside the HREF attribute of A 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 the HREF attribute.

倾城°AllureLove 2024-12-16 15:10:47

将用 http://myurl.com/create/?url=http:// 替换 $string 中每个链接中的每个 http://myoldurl.com /myoldurl.com

$string = preg_replace("/href=\"http:\/\/myoldurl\.com/i", "href=\"http://myurl.com/create/?myoldurl.com", $string);

Will replace every http://myoldurl.com in every link in $string by http://myurl.com/create/?url=http://myoldurl.com:

$string = preg_replace("/href=\"http:\/\/myoldurl\.com/i", "href=\"http://myurl.com/create/?myoldurl.com", $string);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文