Reliable Regex for HTML are difficult. Aquí es cómo hacerlo con DOM:
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
echo $dom->saveHtml($node), PHP_EOL;
}
Lo anterior podría encontrar la salida y la de todos los "outerHTML"A
elementos en la cadena $html
.
Para obtener todos los valores de texto del nodo, lo hace
echo $node->nodeValue;
Para cheque si existe el atributo href
que puede hacer
echo $node->hasAttribute('href');
Para obtener la href
atributo que harías
echo $node->getAttribute('href');
Para cambio la href
atributo que haría
$node->setAttribute('href', 'something else');
Para eliminar la href
atributo que haría
$node->removeAttribute('href');
También puede consultar para el atributo href
directamente con XPath
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//a/@href');
foreach($nodes as $href) {
echo $href->nodeValue; // echo current attribute value
$href->nodeValue = 'new value'; // set new attribute value
$href->parentNode->removeAttribute('href'); // remove attribute
}
Véase también:
En una nota: estoy seguro de que esto es un duplicado y se puede find the answer somewhere in here
La expresión regular fiable para analizar HTML es intrínsecamente imposible incluso si HTML no es un lenguaje normal. – Asciiom