2014-05-11 16 views
5

Voglio estrarre un numero da html, tra <td>...</td>. Ho provato a seguire il codice:Multiple jolly preg_match_all php

$views = "/<td id=\"adv-result-views-(?:.*)\" class=\"spec\">(.*?)<\/td>/"; 

dopo -visure- è un numero casuale. Qual è il codice giusto per ignorare il numero casuale nella ricerca?

+0

Puoi pubblicare un esempio del codice HTML che desideri associare? –

+0

'' Il numero 4 è quello che vorrei ottenere con il preg_match_all – user3625376

+0

'adv-risultato-vista-\ d + ' – bansi

risposta

1

Utilizzando un DOM sarà la strada giusta ..

Procedere in questo modo ...

<?php 
$htm = '<td id="adv-result-views-190147977" class="spec"> 4 </td>'; 
$dom = new DOMDocument; 
$dom->loadHTML($htm); 
echo $content = $dom->getElementsByTagName('td')->item(0)->nodeValue; //4 
+0

non sono i numeri che vorrei estrarre ma il "Sometext" nel tuo esempio. E un DOM non è possibile poiché la classe è usata in più e l'id è casuale. – user3625376

+0

Non penso che tu abbia pienamente compreso la domanda. –

+0

@ user3625376, vuoi dire qualcosa del genere? https://eval.in/149603 –

1
$html = '<td id="adv-result-views-190147977" class="spec"> 4 </td>'; 

// get the value of element 
echo trim(strip_tags($html)); 

// get the number in id attribute, replace string with group capture $1 
echo preg_replace('/^.*?id="[\pLl-]+(\d+).*$/s', '$1', $html); 
/* 
    ^.*?id="   Any character from the beginning of string, not gready 
     id="   Find 'id="' 
      [\pLl-]+ Lower case letter and '-' (1 or more times) 
      (\d+)  Group and capture to \1 -> digits (0-9) (1 or more times) -> end of \1      
    .*$     Any character, gready, until end of the string 
*/ 

// get html withut the number in id attribute 
echo preg_replace('/(^.*?id="[\pLl-]+)(\d+)(.*$)/s', '$1$3', $html); 

Questo è un esempio regex in quanto la questione è etichettato come tale, ma è DOM il modo preferito (specialmente nella community SO) per analizzare il codice HTML.