2

我遇到了一个很难处理的问题。我正在替换 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:// 的链接。

4

4 回答 4

2

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

<?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
);
?>
于 2009-08-10T06:37:42.393 回答
0

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

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

而不是我希望它显示的内容,我希望它像这样显示,并在前面加上 url:

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

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

于 2009-08-10T12:55:36.850 回答
0

这可以解决问题

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

结果:

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

于 2009-08-09T19:57:53.600 回答
0

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

于 2009-08-09T20:07:55.420 回答