2013-07-20 1 views
1

내 문제는 동일한 콘텐츠에 iframe, 이미지 태그 등이 있다는 것입니다. 모두 정규식이있어 올바른 형식으로 변환됩니다.html 태그에없는 URL을 검색 한 다음 하이퍼 링크로 변환하는 방법은 무엇입니까?

마지막으로 남은 것은 일반적인 URL입니다. 나는 iframe, img 또는 다른 태그 안에 링크가 아닌 모든 링크를 찾을 정규식이 필요합니다. 이 경우 사용되는 태그는 BB가 아닌 일반 HTML 태그입니다.

현재이 코드는 콘텐츠 렌더링의 마지막 단계입니다. 하지만 위의 모든 다른 작업 (iframe 및 img 렌더링)에도 반응 할 것입니다. 따라서 URL이 바뀌면 URL도 바뀝니다.

$output = preg_replace(array(
    '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s' 
), array(
    'test' 
), $output); 

그리고 내 콘텐츠는 다음과 같이 보입니다 : 당신이 볼 수 있듯이

# dont want these to be touched 
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe> 
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" /> 

# and only these converted 
http://google.com 
http://www.google.com 
https://www2.google.com<br /> 
www.google.com 

것은, 또한 링크의 끝에 뭔가가있을 수 있습니다. 일할 regexes를 시도의 하루 종일 후, 그 마지막 <br /> 나를 위해 악몽이되었습니다.

+0

정규식이 문제의 해결책이라고 생각하지 않습니다 ... –

답변

2

설명

이 솔루션은하지 태그 안에있는 속성 값을, 새로운 뭔가를 대체 할 URL을 일치합니다.

정규식은 건너 뛴 항목과 교체 한 항목 모두와 일치합니다. 그런 다음 preg_match_callback은 캡처 그룹 1이 채워 졌는지 여부를 테스트하는 내부 함수를 실행하고 (원하는 텍스트) 원하는 경우 변경 사항을 반환하고, 그렇지 않으면 단순히 원하지 않는 텍스트를 반환합니다.

나는 비 캡처 그룹 (?: ... )에 사용되지 않는 캡처 그룹을 ( ... ) 변환처럼 약간 수정하여 URL을 매칭 정규식을 사용했다. 이것은 정규 표현 엔진을 더 빠르게 실행하게하고 표현을 수정하기 쉽게합니다.

원료 식 : <(?:[^'">=]*|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))

enter image description here

코드

<?php 

$string = '# dont want these to be touched 
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe> 
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" /> 

# and only these converted 
http://google.com 
http://www.google.com 
https://www2.google.com<br /> 
www.google.com'; 


    $regex = '/<(?:[^\'">=]*|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*>|((?:[\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|(?:[^[:punct:]\s]|\/)))/ims'; 

    $output = preg_replace_callback(
     $regex, 
     function ($matches) { 
      if (array_key_exists (1, $matches)) { 
       return '<a href="' . $matches[1] . '">' . $matches[1] . '<\/a>'; 
      } 
      return $matches[0]; 
     }, 
     $string 
    ); 
    echo $output; 

출력

,
# dont want these to be touched 
<iframe width="640" height="360" src="http://somedomain.com/but-still-its-a-link-to-somewhere/" frameborder="0"></iframe> 
<img src="http://someotherdomain.com/here-is-a-img-url.jpg" border="0" /> 

# and only these converted 
<a href="http://google.com">http://google.com<\/a> 
<a href="http://www.google.com">http://www.google.com<\/a> 
<a href="https://www2.google.com">https://www2.google.com<\/a><br /> 
<a href="www.google.com">www.google.com<\/a> 
+0

놀라운 대답. 하지만 현재 구문 오류 : 구문 오류, 예기치 않은 T_FUNCTION –

+0

잘 모르겠어요, 그것은 나를 위해 http://ideone.com/dw5SgQ에서 작동합니다. –

+0

잘 나를 위해 콜백 때문에 오류가 발생했습니다 (메신저 5.2.17 버전 사용). 또한 코드에서 정규 표현식 부분을 단순히 사용하면 iframe에서도 모든 항목이 제거됩니다. –

관련 문제