【问题标题】:ignoring img tags while searching for urls in string在字符串中搜索 url 时忽略 img 标签
【发布时间】:2021-03-06 07:52:09
【问题描述】:

我在下面的代码中用超链接的锚标签替换了 url,

public function urlify($string)
{

    //FIND URLS INSIDE TEXT
    //The Regular Expression filter
    $reg_exUrl = "/(((http(s?)(:\/\/))?([w]{3}\.)?)([a-z0-9]+\.)*([a-z|0-9])+\.(com(\.au)?|org|me|net|ly|be|gl|info|(co(\.))?uk|ca|nz|tv)((\/[^\s]+)*)+)/i";

    // Check if there is a url in the text
    if (preg_match($reg_exUrl, $string, $url)) {

        if (strpos($url[0], ":") === false) {
            $link = 'http://' . $url[0];
        } else {
            $link = $url[0];
        }

        // make the urls hyper links
        $string = preg_replace($reg_exUrl, '<a href="' . $link . '" title="' . $url[0] . '" target="_blank">' . $url[0] . '</a>', $string);
    }

    return $string;
}

但我想在搜索 url 时忽略所有 img 标签,我不知道该怎么做。

【问题讨论】:

  • 只需要检查 URL 中是否包含图像文件扩展名。但是,URL 也可能不包含原始文件名(即,出于安全原因生成哈希),在这种情况下,唯一的方法是获取资源并检查其 MIME
  • @biesior 我们不能修改正则表达式来忽略所有img标签吗?
  • 您应该尝试使用 DOMDocument 之类的东西,因为正则表达式很容易导致问题。 DOMDocument 允许您了解内容的上下文以及您正在使用的节点类型。
  • @ShoyebSheikh 检查字符串的方式取决于您,正则表达式就是其中之一。问题在于出于安全原因生成的 URL,例如http://domain.tld/resource.php?id=12345abc。在这种情况下,字符串比较将不起作用。

标签: php regex


【解决方案1】:

根据@Biesor 和@Nigel Ren 我想出了这个,

public function urlify($string)
{

    //FIND URLS INSIDE TEXT
    //The Regular Expression filter
    $reg_exUrl = "/(((http(s?)(:\/\/))?([w]{3}\.)?)([a-z0-9]+\.)*([a-z|0-9])+\.(com(\.au)?|org|me|net|ly|be|gl|info|(co(\.))?uk|ca|nz|tv)((\/[^\s]+)*)+)/i";

    $htmlDom = new DOMDocument;
    $htmlDom->loadHTML($string);
    $imageTags = $htmlDom->getElementsByTagName('img');
    $img_srcs = array();
    foreach($imageTags as $imageTag){
        $img_srcs[] = $imageTag->getAttribute('src');
        $imageTag->setAttribute('src', ''); 
    }        
    $string = $htmlDom->saveHTML();

    // Check if there is a url in the text
    if (preg_match($reg_exUrl, $string, $url)) {

        if (strpos($url[0], ":") === false) {
            $link = 'http://' . $url[0];
        } else {
            $link = $url[0];
        }

        // make the urls hyper links
        $string = preg_replace($reg_exUrl, '<a href="' . $link . '" title="' . $url[0] . '" target="_blank">' . $url[0] . '</a>', $string);
    }

    foreach($imageTags as $key => $imageTag){
        $imageTag->setAttribute('src', $img_srcs[$key]); 
    }
    $string = $htmlDom->saveHTML();
    $p =  $htmlDom->getElementsByTagName('p')->item(0);
    if($p)
    { 
        $string = implode(
            "",
            array_map([$htmlDom, 'saveHTML'], iterator_to_array($p->childNodes))
        );
    }

    return $string;
}

目前我正在使用它,直到出现更好的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多