2012-12-18 2 views
1

이 같은 HTML 템플릿을 가지고 :의 PHP는 preg_match 이미지

<div class="cont"> 
    <div class="..."> 
    <p>...<p> 
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p> 
    .... 

그리고 내가 ""태그 안에 "원하는 이미지 링크"를 추출 할, 현재 나는이 사용하고 있습니다

$pattern = '<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i'; 
if (preg_match($pattern, $content, $image)) 
    ..... 

그러나이 작동하지 않는 오류는 다음과 같습니다

warning: preg_match() [function.preg-match]: Unknown modifier '.' 

내가 그것을 어떻게 해결할 수 있습니까? 감사합니다

답변

3

대답은 정규 표현식을 사용하지 않는다는 것입니다.

$contents = <<<EOS 
<div class="cont"> 
    <div class="..."> 
    <p>...<p> 
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p> 
EOS; 

$doc = new DOMDocument; 
libxml_use_internal_errors(true); 
$doc->loadHTML($contents); 
libxml_clear_errors(); 

$xp = new DOMXPath($doc); 

// get first image inside div.cont 
foreach($xp->query('//div[@class="cont"]//img[1]') as $node) { 
     // output the src attribute 
     echo $node->getAttribute('src'), PHP_EOL; 
} 

은 참조 : DOMDocumentDOMXPath

+0

완벽하게 작동합니다! 감사 – Alvins

0

$pattern = '/<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i

당신은 당신의 최고의 구분 문자 /을 놓치고있어.

+0

는 DOM은 항상 X (HT) ML 유효하지 않습니다 – Alvins

1

html 구문 분석을 계획중인 경우 DOMxpath을 사용해보세요.

+0

을 작동하지 않습니다. 나는 이것을 강력히 권고한다. 간단한 일을 위해서, 정규식은 잘 동작합니다. – Halcyon