【问题标题】:preg_replace change img and link paths to use proxypreg_replace 更改 img 和链接路径以使用代理
【发布时间】:2009-08-09 19:44:42
【问题描述】:

我遇到了一个难以处理的问题。我正在替换 a-tags 和 img-tags 以适应我这样的建议。到目前为止一切顺利。

$search = array('|(<a\s*[^>]*href=[\'"]?)|', '|(<img\s*[^>]*src=[\'"]?)|');
$replace = array('\1proxy2.php?url=', '\1'.$url.'/');
$new_content = preg_replace($search, $replace, $content);

现在我的问题是页面上有链接,我获取的内容如下所示:

<a href="/test/page/">

<a href="http://google.se/test/">

替换这两个链接后的样子是这样的:

<a href="proxy2.php?url=/test/page/">

<a href="proxy2.php?url=http://google.se/test/">

对我来说问题是我想在 /test/page/ 之前包含一个名为 $url 的变量,并且仅在类似的链接上包含,而不是之前已经是 http:// 或 https:// 的链接.

【问题讨论】:

标签: php regex preg-replace


【解决方案1】:

这至少应该为锚标签完成工作:

<?php
function prepend_proxy($matches) {
    $url = 'http://example.prefix';

    $prepend = $matches[2] ? $matches[2] : $url;
    $prepend = 'proxy2.php?url='. $prepend;

    return $matches[1] . $prepend . $matches[3];
}
$new_content = preg_replace_callback(
    '|(href=[\'"]?)(https?://)?([^\'"\s]+[\'"]?)|i',
    'prepend_proxy',
    $content
);
?>

【讨论】:

    【解决方案2】:

    只需让您的 proxy2.php 更智能一点。如果出现完全限定的 URL (http://...),请重定向到该 URL。如果出现本地 URL(例如 /test/page/),则删除缺少的内容(例如 http://www.mylittleapp.com/test/page/)并重定向。

    【讨论】:

    • 但这并不是我真正想要的。我希望每个 URL 都通过这个脚本。
    • 如果你的proxy2.php脚本接收到url=/test/page/,是不是不能确定全限定URL?
    • 我确实使用名为 $url 的变量来确定它是哪个 URL。但这只是test.com 而不是地图等。
    【解决方案3】:

    这样就可以了

    $search = array('@(<a\s*[^>]*href=[\'"]?)(https?://)?@');
    $replace = array('\1proxy2.php?url=');
    $new_content = preg_replace($search, $replace, $content);
    

    结果:


    【讨论】:

    【解决方案4】:

    我是萨拉。 Scronide,您的代码不起作用。它仍然返回:

    <a href="proxy2.php?url=/test/page/">
    <a href="proxy2.php?url=google.se/test/">
    

    而不是我希望它显示的内容,我希望它显示为这样,带有前缀:

    <a href="proxy2.php?url=**THEURLHERE.COM**/test/page/">
    <a href="proxy2.php?url=google.se/test/">
    

    抱歉,它确实有效,我在使用 URL 变量时做错了。谢谢你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2013-10-11
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多