我正在尝试匹配我的内容中的<a>标记,然后将链接文本替换为方括号中的url以用于打印版本。如果只有<!>“; href <!>”,则以下示例有效。如果<=>包含另一个属性,则它匹配太多并且不会返回所需的结果。如何匹配URL和链接文本呢?

这是我的代码:

<?php
$content = '<a href="http://www.website.com">This is a text link</a>';
$result = preg_replace('/<a href="(http:\/\/[A-Za-z0-9\\.:\/]{1,})">([\\s\\S]*?)<\/a>/',
     '<strong>\\2</strong> [\\1]', $content);
echo $result;
?> 

期望的结果:

<strong>This is a text link </strong> [http://www.website.com]

谢谢, 杰森

有帮助吗?

解决方案

您可以使用?进行不匹配的比赛。 您还应该考虑href属性之前可能存在的属性。

$result = preg_replace('/<a [^>]*?href="(http:\/\/[A-Za-z0-9\\.:\/]+?)">([\\s\\S]*?)<\/a>/',
    '<strong>\\2</strong> [\\1]', $content);

其他提示

您应该使用DOM来解析HTML,而不是正则表达式......

编辑:更新了代码,对href属性值进行简单的正则表达式解析。

编辑#2:使循环回归,以便它可以处理多个替换。

$content = '
<p><a href="http://www.website.com">This is a text link</a></p>
<a href="http://sitename.com/#foo">bah</a>

<a href="#foo">I wont change</a>

';


 $dom = new DOMDocument();
    $dom->loadHTML($content);

    $anchors = $dom->getElementsByTagName('a');
    $len = $anchors->length;

    if ( $len > 0 ) {
        $i = $len-1;
        while ( $i > -1 ) {
        $anchor = $anchors->item( $i );

        if ( $anchor->hasAttribute('href') ) {
            $href = $anchor->getAttribute('href');
            $regex = '/^http/';

            if ( !preg_match ( $regex, $href ) ) { 
            $i--;
            continue;
            }

            $text = $anchor->nodeValue;
            $textNode = $dom->createTextNode( $text );

            $strong = $dom->createElement('strong');
            $strong->appendChild( $textNode );

            $anchor->parentNode->replaceChild( $strong, $anchor );
        }
        $i--;
        }
    }

    echo $dom->saveHTML();
    ?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top