preg_replace修改来自curl的SRC和HREF URL

时间:2013-10-04 17:10:26

标签: php url curl preg-replace preg-match

我需要更换curl所采用的页面中的网址,并添加指向图像和链接的正确链接。我的php卷曲代码是:

<?php

function getPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

    $result = curl_exec($ch);
    curl_close($ch);

    if (!preg_match('/src="https?:\/\/"/', $result))
    $result = preg_replace('/src="(.*)"/', "src=\"http://support.prophpbb.com/\\1\"", $result);
    if (!preg_match('/href="https?:\/\/"/', $result))
    $result = preg_replace('/href="(.*)"/', "href=\"http://support.prophpbb.com/\\1\"", $result);
    return $result;
}

$result = getPage('http://support.prophpbb.com/');

print_r ($result);

?>

此代码适用于某些链接,但对于正确的链接,它会重复。

从错误的链接,替换为正确的:

<img src="./uploads/support/images/1355955233.png" alt="" title="" />
<img src="http://support.prophpbb.com/./uploads/support/images/1355955233.png" alt="" title="" />

但正确的链接,被替换为错误:

<img src="http://support.prophpbb.com/styles/subsilverPlus/theme/images/icon_mini_faq.gif" width="12" height="13" alt="*" />
<img src="http://support.prophpbb.com/http://support.prophpbb.com/styles/subsilverPlus/theme/images/icon_mini_faq.gif" width="12" height="13" alt="*" />

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

在preg_replace中试用这个正则表达式

<?php

function getPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

    $result = curl_exec($ch);
    curl_close($ch);

    if (!preg_match('/src="https?:\/\/"/', $result)) {
        $result = preg_replace('/src="(http:\/\/([^\/]+)\/)?([^"]+)"/', "src=\"http://support.prophpbb.com/\\3\"", $result);
    }
    if (!preg_match('/href="https?:\/\/"/', $result)) {
        $result = preg_replace('/href="(http:\/\/([^\/]+)\/)?([^"]+)"/', "href=\"http://support.prophpbb.com/\\3\"", $result);
    }
    return $result;
}

$result = getPage('http://support.prophpbb.com/');

print_r ($result);