0

我正在尝试匹配<a>我的内容中的标签,并将它们替换为链接文本,后跟方括号中的 url 以获取打印版本。

如果只有“href”,则以下示例有效。如果<a>包含另一个属性,则它匹配太多并且不会返回所需的结果。

如何匹配 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]
4

2 回答 2

9

您应该使用 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();
    ?>
于 2009-09-17T16:11:05.713 回答
0

您可以使用?. 您还应该考虑到属性之前可能有href属性。

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