2010-02-19 4 views
0

나는 웹 사이트의 내용을 문자열 $ html에 저장합니다.문자열의 html 링크 수를 계산하고 목록을 추가하십시오.

나는 .OTF 형식의 파일을 사용하고있는 모든 HTML 링크에 이 및 원래 링크를 제거 $의 HTML의 끝에 이러한 링크 목록을 추가 할 수 있습니다.

예 : 나는 그렇게 어떻게

<?php 
$html_input = ' 
<p> 
    Lorem <a href="font-1.otf">ipsum</a> dolor sit amet, 
    consectetur <a href="http://www.cnn.com">adipiscing</a> elit. 
    Quisque <a href="font-2.otf">ultricies</a> placerat massa 
    vel dictum. 
</p>' 

// some magic here  

$html_output = ' 
<p> 
    Lorem ipsum dolor sit amet, 
    consectetur <a href="http://www.cnn.com">adipiscing</a> elit. 
    Quisque ultricies placerat massa 
    vel dictum. 
</p> 
<p>.otf-links: 2</p> 
<ul> 
    <li><a href="font-1.otf">ipsum</a></li> 
    <li><a href="font-2.otf">ultricies</a></li> 
</ul>' 
?>   

? 정규 표현식을 사용해야합니까, 아니면 다른 방법이 있습니까?

+0

아니, 당신은해야하지 사용자 정규 표현식. 참조 : http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 실제 답변은 곧 제공 될 것입니다. –

답변

5
require_once("simple_html_dom.php"); 

$doc = new simple_html_dom(); 
$doc->load($input_html); 

$fonts = array(); 
$links = $doc->find("a"); 

foreach ($links as $l) { 
    if (substr($l->href, -4) == ".otf") { 
     $fonts[]  = $l->outertext; 
     $l->outertext = $l->innertext; 
    } 
} 

$output = $doc->save() . "\n<p>.otf-links: " . count($fonts) ."</p>\n" . 
    "<ul>\n\t<li>" . implode("</li>\n\t<li>", $fonts) . "</li>\n</ul>"; 

Documenation 간단한 HTML DOM http://simplehtmldom.sourceforge.net/

+0

+1 예를 들어. 내 것보다 덜 던져진다. href의 길이가 4보다 작 으면 스크립트가 실패 할 수있는 문제가 수정되었습니다. – Yacoby

+0

노력에 감사드립니다. 이것은리스트에서 ancor 태그를 제거하는 것을 제외하고는 내가 원했던 것입니다. swapping _ $ l-> outertext = $ l-> innertext; _ 및 _ $ fonts [] = $ l; _는 도움이되지 않으므로 어떻게 수정합니까? – snorpey

+0

@ Yacoby Thanks mate; 그러나 문자열 길이가 0 인 경우에도 'substr'은 오류없이 계속 행복하게되므로 검사가 필요하지 않습니다. @snorpey 문제를 해결했습니다. PHP의 오브젝트는 명시 적으로 복제하지 않는 한 참조로 지정됩니다. 수정은 앵커 객체의 실제 문자열 표현을 변경하기 전에'$ fonts []'에 할당하는 것입니다. –

2

사용하십시오 DOM Parser

예 :

$h = str_get_html($html); 

$linkCount = count($h->find('a')); 

foreach ($h->find('a') as $a){ 
    //print every link ending in .odf 
    if (ends_with(strtolower($a->href), '.odf')){ //ends with isn't a function, but it is trivial to write 

     echo '<li><a href="'.$a->href.'">'.$a->innertext.'</a></li>'; 
    } 
} 
+0

+1 돔 파서를 추천합니다. – marcgg

+0

나는 단순한 HTML 돔을 좋아한다! 당신은 저를 때려 눕혔지만 원래 입력에서 앵커 태그를 제거하는 방법을 배제했습니다. –

-1
preg_match('~<a href="[^"]+\.otf">.*?</a>~s', $html_input, $matches); 
$linksCount = count($matches[0]); 
preg_replace('~<a href="[^"]+\.otf">.*?</a>~s', '', $html_input); 
$html_input.='<ul><li>'.implode('</li><li>', $matches[0]).'</li></ul>'; 
+0

우리 모두 regexp를 사용하여 HTML을 구문 분석하면 어떻게되는지 알 수 있습니다 ... http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – marcgg

+0

OP에 대한 경고문. –

관련 문제