Domanda
Ciao voglio estrarre i collegamenti
<a href="/portal/clients/show/entityId/2121" >
e voglio una regex che mi givs / portale / clienti / mostra / EntityID / 2121
il numero alla fine 2121 è in altri link differenti
qualche idea?
Soluzione
Regex per i collegamenti di analisi è qualcosa di simile:
'/<a\s+(?:[^"'>]+|"[^"]*"|'[^']*')*href=("[^"]+"|'[^']+'|[^<>\s]+)/i'
Premesso quanto orribile che è, mi consiglia di utilizzare semplice HTML Dom per ottenere i collegamenti, almeno. È quindi possibile controllare i collegamenti con alcune espressioni regolari molto di base sul href collegamento.
Altri suggerimenti
semplice PHP HTML DOM Parser esempio:
// Create DOM from string
$html = str_get_html($links);
//or
$html = file_get_html('www.example.com');
foreach($html->find('a') as $link) {
echo $link->href . '<br />';
}
Non usare le espressioni regolari per procedando xml / html . Questo può essere fatto molto facilmente utilizzando il incorporato dom parser :
$doc = new DOMDocument();
$doc->loadHTML($htmlAsString);
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('//a/@href');
for ($i = 0; $i < $nodeList->length; $i++) {
# Xpath query for attributes gives a NodeList containing DOMAttr objects.
# http://php.net/manual/en/class.domattr.php
echo $nodeList->item($i)->value . "<br/>\n";
}
Quando "parsing" html Io per lo più contare su PHPQuery: http://code.google.com / p / phpquery / piuttosto che regex.
Questa è la mia soluzione:
<?php
// get links
$website = file_get_contents("http://www.example.com"); // download contents of www.example.com
preg_match_all("<a href=\x22(.+?)\x22>", $website, $matches); // save all links \x22 = "
// delete redundant parts
$matches = str_replace("a href=", "", $matches); // remove a href=
$matches = str_replace("\"", "", $matches); // remove "
// output all matches
print_r($matches[1]);
?>
Vi consiglio di evitare l'uso di parser XML-based, perché non sempre sapere, se il documento / sito web è stato ben formato.
Con i migliori saluti
Link paring da HTML può essere fatto utilizzando parser HTML del mattino.
Quando si dispone di tutti i link, semplice ottenere l'indice dell'ultimo barra, e hai il tuo numero. No regex aveva bisogno.