Ancorare i tag su testo semplice all'interno del contenuto
-
10-07-2019 - |
Domanda
Sto cercando di abbinare <a>
i tag all'interno dei miei contenuti e sostituirli quindi con il testo del link seguito dall'URL tra parentesi quadre per una versione stampata. L'esempio seguente funziona se esiste solo il & Quot; href & Quot ;. Se <=> contiene un altro attributo, corrisponde troppo e non restituisce il risultato desiderato. Come posso abbinare l'URL e il testo del link e il gioco è fatto?
Ecco il mio codice:
<?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;
?>
Risultato desiderato:
<strong>This is a text link </strong> [http://www.website.com]
Grazie, Jason
Soluzione
Puoi rendere la partita non gradita usando ?
.
Dovresti anche tenere presente che potrebbero esserci degli attributi prima dell'attributo href
.
$result = preg_replace('/<a [^>]*?href="(http:\/\/[A-Za-z0-9\\.:\/]+?)">([\\s\\S]*?)<\/a>/',
'<strong>\\2</strong> [\\1]', $content);
Altri suggerimenti
Dovresti usare DOM per analizzare HTML, non espressioni regolari ...
Modifica: codice aggiornato per eseguire semplici analisi regex sul valore dell'attributo href.
Modifica n. 2: ha reso il ciclo regressivo in modo che possa gestire più sostituzioni.
$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();
?>