제임스의 정규식에 대한 개선점은 :
(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>
이 정규식 의지는 문자열 배열 $ follow_list에 링크를하지 일치합니다. 이 문자열에는 앞선 'www'가 필요 없습니다. :) 이 정규식은 태그의 다른 인수 (예 : target, style, title ...)를 보존한다는 점에서 이점이 있습니다.
$1$2$3"$4 rel="nofollow">
전체 예 (PHP) :하십시오 rel
인수가 이미 태그에있는 경우,
가와 교체 정규식이 일치하지 않습니다, 그래서 당신은하지 $의 follow_list의 URL에 다음과 강제 할 수
: 당신이 상관없이
rel
을 덮어 쓰지하려면
function dont_follow_links($html) {
// follow these websites only!
$follow_list = array(
'google.com',
'mypage.com',
'otherpage.com',
);
return preg_replace(
'%(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>%',
'$1$2$3"$4 rel="nofollow">',
$html);
}
, 나는 콜백에서 rel 속성이 개별적으로 대체됩니다 preg_replace_callback
접근 방식을 사용
$subject = preg_replace_callback('%(<a\s*[^>]*href="https?://(?:(?!(?:(?:www\.)?'.implode('|(?:www\.)?', $follow_list).'))[^"]+)"[^>]*)>%', function($m) {
return preg_replace('%\srel\s*=\s*(["\'])(?:(?!\1).)*\1(\s|$)%', ' ', $m[1]).' rel="nofollow">';
}, $subject);
하지 마십시오. http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html – TrueWill
컴퓨터가 작동하지 않습니다! http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – dkarzon
자, 첨부 파일을 읽고 요령을 얻었습니다. 그러나 제 요구 사항은 제한적이며 RegEx를 사용하여 구문 분석하는 것이 유일한 방법입니다. 다음에 감사드립니다. * 일반적으로 좋지 않습니다. (코딩 공포에서). 그 점을 염두에 두십시오. 제 RegEx 코드로 도움을받을 수있는 사람이 있습니까? 내가 왜 정규 표현식을 파싱 할 수 밖에 없는지를 설명 할 수는 있지만, 어쨌든 나쁜 생각이 들더라도 해결책은 필요하다. – Rodney