【问题标题】:How to encode all URL from String using Preg_Replace如何使用 Preg_Replace 对字符串中的所有 URL 进行编码
【发布时间】:2018-09-28 06:12:03
【问题描述】:

我想将所有指向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

【问题讨论】:

  • 通过陈述您想要的确切输出来完成您的问题很重要。此外,如果您尝试解析 html,我们建议您推荐 DomDocument 或类似的工具,而不是正则表达式,因为正则表达式通常不太适合。
  • 第一组和第二组应该是什么?您当前的代码有 7 个组
  • @mickmackusa 如果我使用 domdocument 我知道它只打印我在属性中设置的内容等,但我想要的是找到所有链接,然后用我不想的 base64 编码/解码替换它删除字符串。我认为最好的方法是使用正则表达式。如果你有另一种方式让我知道,所以我可以了解更多。对不起我的英语。

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


【解决方案1】:

我将提供一个“不稳定的解决方案”,因为正则表达式不可靠。我已经适应了单引号、双引号和无引号的 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>

【讨论】:

  • 是否有可能使它更特别,一些链接添加包含和排除。例如用awsub.co 编码链接,但不要用safelinkconverter.com 编码链接。
  • 如果修改模式变得过于复杂,您可以不考虑模式,只需在$m[1] 的返回行上写一个strpos() 条件。我不在电脑旁,因此无法提供更具体的支持。
  • 这是我建议的(*SKIP)(*FAIL) 模式:regex101.com/r/EFSIej/3
  • 工作,但我尝试添加更多链接以排除 anotherlink.com 并将正则表达式修改为 (?:safelinkconverter\.com|anotherlink.com)(*SKIP)(*FAIL)| 你可以看到问题,我更新我的代码。它跳过safelink,但仍然编码anotherlink.com
  • 我把它和它的工作一样分组(?:safelinkconverter\.com|anotherlink\.com)regex101.com/r/EFSIej/6谢谢你的帮助@mickmackusa
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 2011-10-06
  • 1970-01-01
  • 2015-03-22
  • 2010-09-18
  • 2010-10-26
  • 1970-01-01
相关资源
最近更新 更多