如何使用 Preg_Replace 对字符串中的所有 URL 进行编码

How to encode all URL from String using Preg_Replace

我想将所有链接编码为 base64,但正则表达式模式未按预期工作。

这是我的代码:

$html = 'ahsgdjagshjdgasjdgajgsd gjagdjhagsjhgda sgdhjagsjdgajhgdjad<a href="http://short.awsubs.co/be9Vk">Solidfiles</a> jashd sha7st7atsdgasgda sgahsfd ahgsfafd<a href=https://link.safelinkconverter.com/review.php?id=aHR0cDovL2JfdC5seS8ySDdMajh3&c=1&user=61942 rel=nofollow>Zippyshare</a>';
$text = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@';
echo $result = preg_replace_callback($text, function($matches) {
    return '<a href="'.base64_encode($matches[1]).'">'.$matches[2].'</a>';
    }, $html);

我读过这个建议使用 preg_replace_callback() 来编码 href 值的帖子:

我将提供一个 "unstable solution",因为正则表达式不可靠。我已经适应了单引号、双引号和无引号的 href 属性。但我必须敦促您使用 html 解析器。您的示例输入不太现实,无法尝试编写 DomDocument 解决方案。

不稳定的代码:(Demo) (Pattern Demo)

$html = 'ahsgdjagshjdgasjdgajgsd gjagdjhagsjhgda sgdhjagsjdgajhgdjad<a href="http://short.awsubs.co/be9Vk">Solidfiles</a> jashd sha7st7atsdgasgda sgahsfd ahgsfafd<a href=https://link.safelinkconverter.com/review.php?id=aHR0cDovL2JfdC5seS8ySDdMajh3&c=1&user=61942 rel=nofollow>Zippyshare</a>';

echo preg_replace_callback('~href=[\'"]?([^\s\'"]+)[\'"]?(.*?)>(.*?)</a>~', function($m) {
    var_export($m);
        return "<a href=\"" . base64_encode($m[1]) . "\"{$m[2]}>{$m[3]}</a>";
    }, $html);

输出:

ahsgdjagshjdgasjdgajgsd gjagdjhagsjhgda sgdhjagsjdgajhgdjad<a <a href="aHR0cDovL3Nob3J0LmF3c3Vicy5jby9iZTlWaw==">Solidfiles</a> jashd sha7st7atsdgasgda sgahsfd ahgsfafd<a <a href="aHR0cHM6Ly9saW5rLnNhZmVsaW5rY29udmVydGVyLmNvbS9yZXZpZXcucGhwP2lkPWFIUjBjRG92TDJKZmRDNXNlUzh5U0RkTWFqaDMmYz0xJnVzZXI9NjE5NDI=" rel=nofollow>Zippyshare</a>