2009-07-24 2 views
1

이 코드에서 내가하고있는 실수가 무엇인지 물어보고 싶습니다. 현재 이미지 태그 또는 객체 태그의 첫 번째 항목을 찾은 다음 일치하는 HTML 태그를 반환하려고합니다. 현재 이미지 태그를 얻을 수 있지만 불행히도 개체 태그에 어떤 결과도없는 것 같습니다.PHP : 문자열의 첫 번째 img 또는 object 태그를 찾으십시오.

나는 정규식 패턴이나 뭔가에서 실수를하고 있다고 생각합니다. 호프 요구 사항은 당신이 감사를 이해할만큼 명확하다. 여기

내 코드 :

function get_first_image(){ 
     global $post, $posts; 
     $first_img = ''; 
     ob_start(); 
     ob_end_clean(); 
     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) || preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches); 
     $first_img = $matches [1] [0]; 

     if(empty($first_img)){ //Defines a default image 
     $mediaSearch = preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches2); 
     $first_media = $matches2 [1] [0]; 
     $first_img = "/images/default.jpg"; 
     } 

     if(!empty($first_img)){ 
     $result = "<div class=\"alignleft\"><img src=\"$first_img\" style=\"max-width: 200px;\" /></div>"; 
     } 

     if(!empty($first_media)){ 
     $result = "<p>" . $first_media . "</p>"; 
     } 

     return $result; 
    } 

답변

2

이 시도 : 정규 표현식은 매우 다양한 좋을 수 있지만

function get_first_image(){ 
     global $post, $posts; 
     $first_img = ''; 
     ob_start(); 
     ob_end_clean(); 
     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) || preg_match_all('(/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>)/smi', $post->post_content, $matches); 
     $first_img = $matches [1] [0]; 

     if(empty($first_img)){ //Defines a default image 
     $mediaSearch = preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches2); 
     $first_media = $matches2 [1] [0]; 
     $first_img = "/images/default.jpg"; 
     } 

     if(!empty($first_img)){ 
     $result = "<div class=\"alignleft\"><img src=\"$first_img\" style=\"max-width: 200px;\" /></div>"; 
     } 

     if(!empty($first_media)){ 
     $result = "<p>" . $first_media . "</p>"; 
     } 

     return $result; 
    } 
+0

글쎄, 현재 개체 태그를 검색하는 기능을하려고합니다 ... – user143805

+0

Ah ... 스크롤 막대 때문에 볼 수 없습니다. 흥미로운 ... –

+0

돌아오고 싶은 것을 결코 정의하지 마십시오. 당신은 '(' ')을 당신이 원하는 배열 주위에 놓을 필요가있다. –

3

을 (당신은 당신이 일치하는 배열에 들어갈 원하는 것을 정의 할 필요가있다) 작업의 경우 HTML DOM을 파싱 할 때 대개 짧은 것으로 나타납니다. HTML의 문제점은 문서의 구조가 가변적이어서 정확하기 어렵고 (정확하게 말하면 거짓 긍정없이 100 %의 성공률을 의미 함) 태그를 추출한다는 것입니다.

내가 추천 당신은 무엇을 SimpleHTML로 같은 DOM 파서를 사용하고 등을 사용하면된다 :

function get_first_image(){ 
    global $post, $posts; 

    require_once('SimpleHTML.class.php') 

    $post_dom = str_get_dom($post->post_content); 

    $first_img = $post_dom->find('img', 0); 

    if($first_img !== null) { 
     $first_img->style = $first_img->style . ';max-width: 200px'; 
     return '<div class="alignleft">' . $first_img->outertext . '</div>'; 
    } else { 
     $first_obj = $post_dom->find('object', 0); 

     if($first_obj !== null) { 
      return '<p>' . $first_obj->outertext . '</p>'; 
     } 
    } 

    return '<div class="alignleft"><img src="/images/default.jpg" style="max-width: 200px;" /></div>'; 
} 

일부는이 잔인한 생각했지만 결국, 또한 유지하기 쉬울 것이다 더 많은 확장 성을 허용합니다. 예를 들어 DOM 파서를 사용하여 현재 이미지의 스타일을 추가 할 수 있습니다.

동일한 목표를 달성하기 위해 정규 표현식을 고안 할 수는 있지만 style 속성이 src 또는 그 반대 문자 뒤에 오도록 제한되어 있으며이 제한을 극복하면 정규 표현식에 더 많은 복잡성이 추가됩니다 표현.

또한 다음을 고려하십시오. 제대로 정규 표현식을 사용하여 <img> 태그를 일치하기 만 src 속성을 얻기 위해 (2 군에서 캡처) 다음과 같은 정규 표현식이 필요합니다 다음 다시

<\s*?img\s+?[^>]*?\s*?src\s*?=\s*?(["'])((\\?+.)*?)\1[^>]*?> 

과, 위에서 언급 한 실패 할 경우 :

  • 속성 또는 태그 이름이 대문자이고 i 수정자가 사용되지 않습니다.
  • src 속성은 따옴표가 사용되지 않습니다.
  • 다른 속성 인 src> 문자를 값의 어딘가에 사용합니다.
  • 내가 예상하지 못한 몇 가지 다른 이유.

다시 말해, dom 문서를 구문 분석하기 위해 정규식을 사용하지 마십시오.

관련 문제