コンテンツ内のプレーンテキストへのアンカータグ
-
10-07-2019 - |
質問
コンテンツ内の<a>
タグを一致させ、印刷テキストの場合は角かっこで囲まれたURLが後に続くリンクテキストに置き換えようとしています。次の例は、<!> quot; href <!> quot;のみがある場合に機能します。 <=>に別の属性が含まれている場合、一致が多すぎるため、目的の結果が返されません。 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();
?>
所属していません StackOverflow