2011-10-25 5 views
1

인 모든 h 태그 특정 페이지 (현 이유)에 대한 모든 h 태그 테이블을 만들고 그 테이블을 채우려합니다. 순간preg_match_all 출력 유형이 모두

 $str = file_get_contents($Url); 
     if(strlen($str)>0){ 
      preg_match_all(" /<(h\d*)>(\w[^<]*)/i",$str,$headings); 

      foreach ($headings as $val) { 
       echo "type: " . $val[1] . "\n"; 
       echo "content: " . $val[2] . "\n"; 
      } 
     } 

난 그냥 그들을 밖으로 반향이 내가이 자사의 확률값 뭔가 잘못 생각 때문에 정규 표현식을 사용하여 이제까지 나의 처음 이상한 결과를 얻고있다.

또한 누군가가 배열 preg_match_all을 처리하는 좋은 지침서를 알고 있다면 그것은 좋을 것입니다.

+1

은 첫째로 당신은 당신의 인생을 어떻게 든에 의존하지 않는 HTML/XML 등을 분석 할 정규식을 사용하지 않아야합니다. 둘째로 나는 "타입"이 무엇을 의미하는지 모른다. 구체적인 입력과 원하는 출력을 제공 할 수 있습니까? – FailedDev

+0

미안 유형은 h 태그 (h1, h2, h3 등)의 종류입니다. 표 유형 및 내용 (실제 텍스트)을 원하면 사용해야합니까? –

+0

'preg_match_all '의 네 번째 매개 변수로'PREG_SET_ORDER'가 누락되었습니다. – mario

답변

2

. 그러나 preg_match_all은 대개 일치 그룹별로 정렬 된 결과 배열을 반환합니다. 우리가 할 수있는 경우 BTW,

preg_match_all("/<(h\d*)>(\w[^<]*)/i",$str,$headings, PREG_SET_ORDER); 

, 이것은 완벽하게 합법적 인 사용이다 (실패 가능성) 정규 표현식의 사용 : 그러나 이는 당신의 foreach는 그것을 기대하는 방법입니다, preg_match_all에 네 번째 매개 변수로 PREG_SET_ORDER 플래그를 추가 할 수 있습니다 헤드 라인 테이블을 추가하기 위해 자신의 응용 프로그램 출력에 대해 작업하고 있다고 가정합니다.

0

정규 표현식에 대해 더 알고 싶다면 좋은 책을 구입하는 것이 좋습니다. 또는 좋은 자습서 용 Google. 개인적으로 내가 좋아하는 것 regular-expressions.info

preg_match_all에 관한 모든 정보는 공식 문서 here에서 찾을 수 있습니다. PHP 커뮤니티는 보통 매뉴얼 페이지에서 유용한 코드를 공유한다. 나는 당신이 원하는 정보를 찾을 수 있다고 생각한다. 당신은 페이지의 전체 HTML 콘텐츠를 구문 분석하는 경우

php > $ch = curl_init('http://stackoverflow.com/questions/7883392/preg-match-all-output-all-h-tags-with-type');            
php > curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); 
php > preg_match_all("!<h(\d)[^>]*>(.*?)</h\\1>!ism",$data,$headings); 
php > var_export($headings); 
array (      
    0 =>      
.... 
2 => 
    array (
    0 => '<a href="https://stackoverflow.com/questions/7883392/preg-match-all-output-all-h-tags-with-type" class="question-hyperlink">preg_match_all output all h tags with type</a>', 
    1 => '', 
    2 => ' 
      Know someone who can answer? 
      Share a <a href="https://stackoverflow.com/q/7883392">link</a> to this question via 
      <a href="mailto:?subject=Stack%20Overflow%20Question&amp;body=preg_match_all%20output%20all%20h%20tags%20with%20type%0Ahttp%3a%2f%2fstackoverflow.com%2fq%2f7883392">email</a>, 
      <a href="http://twitter.com/share?url=http%3a%2f%2fstackoverflow.com%2fq%2f7883392&amp;text=preg_match_all%20output%20all%20h%20tags%20with%20type">twitter</a>, or 
      <a href="http://www.facebook.com/sharer.php?u=http%3a%2f%2fstackoverflow.com%2fq%2f7883392&amp;t=preg_match_all%20output%20all%20h%20tags%20with%20type">facebook</a>. 
     ', 
    3 => 'Your Answer', 
    4 => ' 
      Browse other questions tagged <a href="https://stackoverflow.com/questions/tagged/php" class="post-tag" title="show questions tagged \'php\'" rel="tag">php</a> <a href="https://stackoverflow.com/questions/tagged/preg-match-all" class="post-tag" title="show questions tagged \'preg-match-all\'" rel="tag">preg-match-all</a> 
       or <a href="https://stackoverflow.com/questions/ask">ask your own question</a>. 
     ', 
    5 => 'Hello World!', 
    6 => 'Related', 
), 
) 
0

, 나는 당신이 PHP's DomDocument을 시도 추천 할 것입니다 : 당신의 정규식은 이미 잘 작동했다

$str = file_get_contents($Url); 

$dom = new DomDocument(); 
$dom->loadHTML($str);   

$hs = array(); 
for($type=1; $type<6; $type++) 
{ 
    $h_es = $dom->getElementsByTagName('h'.$type); 
    foreach($h_es as $h) 
    { 
    $hs[] = array('type'=>$type, 'content'=>$h->textContent); 
    } 
} 

print_r($hs); 
1

사용이 메소드는 제목 태그, 자신의 유형 및 인스턴스와 연관 배열을 반환 :

public function getHeadingTags() 
{ 
    preg_match_all("#<h(\d)[^>]*?>(.*?)<[^>]*?/h\d>#i", 
        $this->html, 
        $matches, 
        PREG_PATTERN_ORDER 
       ); 
    $headings = array(); 
    foreach ($matches[1] as $key => $heading_key) { 
     $headings["h$heading_key"][] = $matches[2][$key]; 
    } 

    ksort($headings); 
    return $headings; 
}