2013-07-08 2 views
2

내부 사용자 정의 URL 문자열을 얻을 :PHP는 정규식이 같은 페이지의 콘텐츠를 HREF 태그

$html = file_get_contents('example.ir'); 

가 지금은 사용자 정의 URL + 문자열해야 $ html로 내부 HREF 태그를 얻을 싶어;

1- href="http://example.ir/salam/ali/...." => http://example.ir/ + salam/ali/.... 
2- href="http://example.ir/?id=123/..."  => http://example.ir/ + ?id=123/... 
3- href="?kambiz=khare/..."     => ?kambiz=khare/... 

내가 숫자 1과 2가 있기 때문에이 원하는 http://example.ir + 일부 문자열을 : 예를 들어

내가 세 href가 있습니다.

Resault을 다음과 같이해야 :

1- http://example.ir/salam/ali/.... 
2- http://example.ir/?id=123/... 

도움말 날 PLZ :

답변

2

이 정규식 그들이 값이 http://example.ir/로 시작하는 href 속성을 제공하는 앵커 태그를 캡처합니다

설명 . 그런 다음 캡처 그룹으로 마지막 줄은 잠재적으로 어려운 가장자리 경우가 있습니다 1.

<a\b(?=\s) # capture the open tag 
(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\shref="(http:\/\/example\.ir\/[^"]*)) # get the href attribute 
(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?> # get the entire tag 
.*?<\/a> 

enter image description here

샘플 텍스트

주 전체 HREF 값을 캡처합니다. 단지 어떻게 경기의 작품을 보여

<a href="http://example.ir/salam/ali/....">salam ali</a> 
<a class="Fonzie" href="http://example.ir/?id=123/...">plus id 123</a> 
<a class="Fonzie" href="?kambiz=khare/...">not an http</a> 
<a onmouseover=' href="http://example.ir/salam/ali/...." ; funHrefRotater(href) ; " href="?kambiz=khare/...">again not the line we are looking for</a> 

코드

이 PHP의 예입니다.

<?php 
$sourcestring="your source string"; 
preg_match_all('/<a\b(?=\s) # capture the open tag 
(?=(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?\shref="(http:\/\/example\.ir\/[^"]*)) # get the href attribute 
(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"\s]*)*"\s?> # get the entire tag 
.*?<\/a>/imx',$sourcestring,$matches); 
echo "<pre>".print_r($matches,true); 
?> 

일치

[0][0] = <a href="http://example.ir/salam/ali/....">salam ali</a> 
[0][1] = http://example.ir/salam/ali/.... 
[1][0] = <a class="Fonzie" href="http://example.ir/?id=123/...">plus id 123</a> 
[1][1] = http://example.ir/?id=123/... 
+0

내가 당신에게 사람 : 니스 그리고 당신이 내 문제를 해결 위대한 설명을 사랑 : ***** –

+0

은 다행 내가 :) 도움이 될 수 –

관련 문제