如何使用Preg_Replace对String中的所有URL进行编码

时间:2018-04-18 06:06:01

标签: php regex encoding href preg-replace-callback

我想将我的所有链接编码为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值进行编码:

php how to do base64encode while doing preg_replace

1 个答案:

答案 0 :(得分:1)

由于正则表达式不可靠,我将提供“不稳定的解决方案”。我已经适应了单引号,双引号和无引用的href属性。但我必须敦促你使用HTML解析器。您打算尝试编写DomDocument解决方案时,您的示例输入不太现实。

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

x

输出:

y