javascript 我如何在一个段落中找到没有http://或https://的URL,并将它们放在前面以确保协议是正确的?[副本]

0yg35tkg  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(97)

此问题已在此处有答案

Transform relative path into absolute URL using PHP(13个回答)
Replace all relative URLs with absolute URLS(2个答案)
How do you parse and process HTML/XML in PHP?(31答案)
2天前关闭。
截至2天前,社区正在审查是否重新讨论此问题。
我有一个来自所见即所得编辑器的请求,看起来像这样

"<p>Testing if urls work <a href=\"google.com\" rel=\"noopener noreferrer\" target=\"_blank\">google.com</a>google.com</p> this is some more content that might be added to the url <a href="www.google.com">www.Google.com</a> with some more text that follows. "

我已经找到了很多例子,我可以使用正则表达式来查找包含https或http的URL,但似乎没有什么可以让我更新段落中的URL。理想情况下,我正在寻找任何没有http或https的内容,并将其添加到URL中。我不介意将解决方案应用于后端或前端。
这就是我想要的结果

"<p>Testing if urls work <a href=\"https://google.com\" rel=\"noopener noreferrer\" target=\"_blank\">google.com</a>google.com</p> this is some more content that might be added to the url <a href="https://www.google.com">www.Google.com</a> with some more text that follows. "
gcuhipw9

gcuhipw91#

你可以使用类似这样的东西来转换你的字符串:

<?php

$str = '<p>Testing if urls work <a href=\"google.com\" rel=\"noopener noreferrer\" target=\"_blank\">google.com</a>google.com</p><p>Testing if urls work <a href=\"http://google.com\" rel=\"noopener noreferrer\" target=\"_blank\">google.com</a>google.com</p> this is some more content that might be added to the url <a href="https://www.google.com">www.Google.com</a> with some more text that follows.';

function checklinks($str){
    
    $str = str_replace("\\", "", $str);
    
    $callback = function($match){
        
        if (!preg_match('/https:\/\//i', $match[1])) {
            
            if (preg_match('/http:\/\//i', $match[1])) $urlstr = '<a href="https://' . substr($match[1], 7) . '"';
            elseif (preg_match('/http\/\//i', $match[1])) $urlstr = '<a href="https://' . substr($match[1], 6) . '"';
            else $urlstr = '<a href="https://' . $match[1] . '"';
        
        } else $urlstr = '<a href="' . $match[1] . '"';
        
        return $urlstr;
    };
    
    if (preg_match('/<a\s+href="([^"]+)"/i', $str)) {
        $str = preg_replace_callback('/<a\s+href="([^"]+)"/i', $callback, $str);
    }
    
    return $str;    
}

echo htmlentities($str) . '<br><br>';

echo htmlentities(checklinks($str));

?>

使用该函数后,结果将是:

<p>Testing if urls work <a href="https://google.com" rel="noopener noreferrer" target="_blank">google.com</a>google.com</p><p>Testing if urls work <a href="https://google.com" rel="noopener noreferrer" target="_blank">google.com</a>google.com</p> this is some more content that might be added to the url <a href="https://www.google.com">www.Google.com</a> with some more text that follows.

相关问题