如何仅在满足条件时使用预置替换


How to use preg-replace only when a condition is met

我已经有可以替换链接的代码,例如

$pattern = "/href=[''"]{0,1}('/|http:'/'/)/";
$replacement = "href=http://example.com/index.php?go=''1";
$string = preg_replace($pattern, $replacement, $html);

这适用于任何包含"http"的链接,但现在我需要用不同的替换替换缺少"http"的链接,例如......

 href="/images/some.gif"

需要更改为...

href="http://example.com/images/some.gif"

有时链接可能是这样的

href="images/some.gif" without the / or even without the ".

希望您正在尝试匹配

href="http://example.com/images/some.gif"
href="images/some.gif"

并替换为

href="http://example.com/index.php?go=http://example.com/images/some.gif"
href="http://example.com/index.php?go=images/some.gif"

请尝试此模式并替换:

$pattern = '(href=["'']){1}(http:'/'/)?([a-z0-9_'-.'/]*)("|''){1}';
$replacement = 'href="http://example.com/index.php?go=$2$3"';

现场演示

[编辑]

根据您的评论,如果要匹配无引号的 HTML 属性值,请将?附加到["'']使其["'']?并将("|''){1}更改为("|'')?。它不是标准的 HTML,但不建议这样做。

$pattern = '(href=["'']?){1}(http:'/'/)?([a-z0-9_'-.'/]*)("|'')?'

更新的现场演示

使用preg_replace_callback应该可以解决它.
像这样的东西——

$html_list = Array(
                'href="images/some.gif"',
                'href="/images/some.gif"', 
                'href="http://example.com/images/some.gif"',
                'href=some.gif'
            );
$pattern = "/((?:href)=[''"]{0,1})(?:('/)|([a-zA-Z])|(http:'/'/))/";
$replacement = "href=http://example.com/index.php?go=''1";
foreach($html_list as $html){
    $string = preg_replace_callback($pattern,
                function($m){
                    //print_r($m);
                    $r = $m[1];
                    if(!empty($m[2])){
                        return $r.'http://example.com/';
                    }if(isset($m[3]) && !empty($m[3])){
                        return $r.'http://example.com/'.$m[3];
                    }
                    //This matches http part
                    return $r.'http://example.com/index.php?go=';
                }
                , $html);
    print_r($string."'n");
}

输出-

href="http://example.com/images/some.gif"
href="http://example.com/images/some.gif"
href="http://example.com/http://example.com/images/some.gif"
href=http://example.com/some.gif

您可以使用:

$html = preg_replace('~((?:src|href)=["'']?)(?!http://)/?~', '$1http://', $html);

正则表达式演示

但是,您应该考虑使用 DOM 可靠地操作 HTML。