2014-05-11 2 views
5

<td>...</td> 사이의 html 숫자를 추출하고 싶습니다. 나는 코드를 따르려고 노력했다 :여러 와일드 카드 preg_match_all ph

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

after -views-는 난수이다. 검색에서 임의의 숫자를 무시하는 올바른 코드는 무엇입니까?

이 방법을 진행

+0

일치시킬 html의 예를 게시 할 수 있습니까? –

+0

'' 수 4 내가 – user3625376

+0

'ADV-결과-조회수 - 그 \으로, preg_match_all으로 좀하고 싶습니다 것입니다 d +' – bansi

답변

1

올바른 방법이 될 것입니다 DOM를 사용하여 ... ...

<?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

내가 추출하고자하는 숫자가 아니라 예제에서 "본질적"인 숫자입니다. 클래스가 복수 '에 사용되고 DOM이 무작위이므로 DOM을 사용할 수 없습니다. – user3625376

+0

나는 그 질문을 완전히 이해했다고 생각하지 않는다. –

+0

@ user3625376,이 같은 것을 의미합니까? 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); 

문제가 같은 태그가 있기 때문에이 정규식 예이지만, DOM입니다 html 구문 분석에 선호되는 방법 (특히 SO 커뮤니티).