【问题标题】:PHP regex to clean a specific string from URLs onlyPHP 正则表达式仅从 URL 中清除特定字符串
【发布时间】:2013-10-24 21:47:00
【问题描述】:

任何正则表达式忍者都想出一个 PHP 解决方案来清除任何 http/url 中的标签,但将标签留在文本的其余部分?

例如:

the word <cite>printing</cite> is in http://www.thisis<cite>printing</cite>.com

应该变成:

the word <cite>printing</cite> is in http://www.thisisprinting.com

【问题讨论】:

  • 相当艰巨的任务,你有没有详细说明?
  • 匹配 url 并不容易,人为错误,例如在句号 . 后没有放置空格,可能会造成严重破坏。您可以保证网址的哪些部分存在,即https?://|www。如果你能保证某些字符串会存在,那么删除标签就不难了

标签: php regex url


【解决方案1】:

这就是我会做的:

<?php
//a callback function wrapper for strip_tags
function strip($matches){
    return strip_tags($matches[0]);
}

//the string
$str = "the word <cite>printing<cite> is in http://www.thisis<cite>printing</cite>.com";
//match a url and call the strip callback on it
$str = preg_replace_callback("/:\/\/[^\s]*/", 'strip', $str);

//prove that it works
var_dump(htmlentities($str));

http://codepad.viper-7.com/XiPcs9

【讨论】:

    【解决方案2】:

    此替换的适当正则表达式可能是:

    #(https?://)(.*?)<cite>(.*?)</cite>([^\s]*)#s
    
    1. s 标志以匹配所有换行符。

    2. 在标签之间使用lazy 选择是为了准确而不是逃避更多相似的标签

    片段:

    <?php
    $str = "the word <cite>printing<cite> is in http://www.thisis<cite>printing</cite>.com";
    $replaced = preg_replace('#(https?://)(.*?)<cite>(.*?)</cite>([^\s]*)#s', "$1$2$3$4", $str);
    echo $replaced;
    
    // Output: the word <cite>printing<cite> is in http://www.thisisprinting.com
    

    Live demo

    【讨论】:

    • 我建议不要使用(.*?),而是使用([^\s]*?)。按照您的操作方式,如果 url 是没有引用标签的字符串的第一部分,则后续的 &lt;cite&gt; 标签将从后面的文本中删除。
    • 这是一个很好的开始 - @JonathanKuhn 的添加是无价的。我将如何捕获 URL 中字符串的第二个(第三个等)实例?例如:https://appleid.apple.com
    【解决方案3】:

    假设您可以从文本中识别 URL,您可以:

    $str = 'http://www.thisis<cite>printing</cite>.com';
    $str = preg_replace('~</?cite>~i', "", $str);
    echo $str;
    

    输出:

    http://www.thisisprinting.com
    

    【讨论】:

    • @HamZa:假设 $str = 'http://www.thisis&lt;cite&gt;printing&lt;/cite&gt;.com'; 不是完整的 HTML 文本。
    • 您在这里省略了printing,但他希望输出为http://www.thisisprinting.com
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2017-08-24
    • 2012-03-21
    • 2022-11-19
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多