이 솔루션은 DOMDocument 및 관련 클래스를 사용하여 html을 구문 분석하고 이미지 요소를 찾은 다음 올바른 src
특성이없는 요소를 제거합니다. 그것은 src 속성과 일치하는 간단한 정규 표현식을 사용하여 문자열의 시작
/^smilies\/smily(One|Two)\.png$/
^
하고 $
은 끝을; /
및 .
은 모두 정규 표현식에서 특수 문자이므로 백 슬래시로 이스케이프됩니다. (One|Two)
은 One
또는 Two
을 의미합니다.
$dom = new DOMDocument;
$dom->loadHTML($html); // your text to be filtered is in $html
// iterate through all the img elements in $html
foreach ($dom->getElementsByTagName('img') as $img) {
# eliminate images with no "src" attribute
if (! $img->hasAttribute('src')) {
$img->parentNode->removeChild($img);
}
# eliminate images where the src is not smilies/smily(One|Two).png
elseif (1 !== preg_match("/^smilies\/smily(Two|One)\.png$/",
$img->getAttribute("src"))) {
$img->parentNode->removeChild($img);
}
// otherwise, the image is OK!
}
$output = $dom->saveHTML();
# now strip out anything that isn't an <img> tag
$html = strip_tags($output, "<img>");
echo "html now: $html\n\n";
[strip_tags']에 대한 문서 (http://php.net/manual/en/function.strip-tags.php)를 확인하십시오 - 지금이 문서를 사용하고 있습니다. –
속성이있는 html 태그와 함께 strip 태그를 사용할 수 있는지 알고 계십니까? 방법 고마워. – www139
'strip_tags'에서 속성을 지정할 수 없습니다 - 문제를 해결하는 가장 좋은 방법은 이미지 태그를 제외하고 모든 것을 제거한 다음 정규 표현식을 사용하여 img 태그를 선택적으로 제거하는 것입니다. 또는 DOMDocument (또는 유사한 XML/HTML 파서)를 사용하여 텍스트를 구문 분석하고 선택적으로 이미지 태그를 제거 할 수 있습니다. –