Jas*_*lme 0 php regex preg-replace
我正在尝试匹配<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;
?>
Run Code Online (Sandbox Code Playgroud)
期望的结果:
<strong>This is a text link </strong> [http://www.website.com]
Run Code Online (Sandbox Code Playgroud)
谢谢你,杰森
您应该使用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();
?>
Run Code Online (Sandbox Code Playgroud)