2012-03-13 6 views
0

를 사용하여 DIV 내에서 태그 요소의 목록을 가져 I 다음 DIV 있습니다는 preg_match

<div class="divClass">Language: 
    <a href="http://www.some-site.com/something/something2/">EN</a> 
    <a href="http://de.some-site.com/something/something2/">DE</a> 
    <a href="http://es.some-site.com/something/something2/">ES</a> 
    <a href="http://fr.some-site.com/something/something2/">FR</a> 
    <a href="http://it.some-site.com/something/something2/">IT</a> 
    <a href="http://nl.some-site.com/something/something2/">NL</a> 
    <a href="http://pt.some-site.com/something/something2/">PT</a> 
    <a href="http://ru.some-site.com/something/something2/">RU</a> 
    <a href="http://gr.some-site.com/something/something2/">GR</a> 
    <a href="http://cn.some-site.com/something/something2/">CN</a> 
    <a href="http://pl.some-site.com/something/something2/">PL</a> 
    <a href="http://se.some-site.com/something/something2/">SE</a> 
</div> 

그리고이 정규식 패턴을 사용하여 :

/<div class="divClass"><a href="(.*)">(.*)<\/a><\/div>/i 

는 다음 식에 사용하려면 :

$out=preg_replace('/<div class="divClass"><a href="(.*)">(.*)<\/a><\/div>/i',replace_link(substr('$1', strpos('$1','com/')+1),'$2'),$out); 

내 preg_replace가 NULL을 반환합니다. 기본적으로 나는 A 태그 내에서 링크를 가져오고 싶고 값이고 링크와 값을 내 replace_link 함수에서 얻은 값으로 대체합니다.

이상형은 어떻게 할 수 있습니까?

감사합니다.

+1

왜 HTML 구문 분석기가 아닌 정규식을 사용하고 있습니까? ಠ_ಠ –

+0

HTML 파서를 사용하고 전체 콘텐츠에 대해 정규 표현식을 사용하는 대신 DOM 요소 및 해당 속성을 사용하는 것이 좋습니다. –

+0

내 특정 시나리오에서 html 파서를 올바르게 사용하는 방법을 모르겠다. DOMDocument를 선호합니다. 어떤 이상이 DOMDocument 함께 할 방법? – Gabriel

답변

1

정규식이 좋지 않습니다 : <a href=...> </a>과 일치하며 많은 것을 제공합니다.

당신은 같은 것을 사용해야합니다 :

/<div class="divClass">\(<a href="(.*)">(.*)<\/a>\)+<\/div>/i 

(PHP에서 비 캡처 구문의 확실하지 않은)

그리고 당신은 또한 공간 (공간 문자, 탭, 라인의 끝 처리해야)를 입력하십시오. 이것은 당신이 DomDocument 사용하는 방법입니다

/<div class="divClass">[^<]*(<a href="(.*)">(.*)<\/a>[^<]*)+[^<]*<\/div>/i 
1

: 당신이 당신의 입력해야합니다 경우 , 당신은 같은 것을 사용할 수 있습니다 당신이 한 단계 더 걸릴하고 싶은 경우 http://codepad.org/RxZ7URMB

// Create new DomDocument 
$doc = new DomDocument(); 
$doc->loadHTML($html); 

// Get all <a> 
$anchors = $doc->getElementsByTagName('a'); 

foreach ($anchors as $a) { 
    echo $a->getAttribute('href') . PHP_EOL; 
} 

당신의 대체 : http://codepad.org/diqRQhiZ

foreach ($anchors as $a) { 
    $a->setAttribute('href', replace_link($a->getAttribute('href'))); 
} 

echo $doc->saveHTML();