HTML to TXT(html2txt) 태그를 삭제 후 텍스트만 반환
내장함수에 strip_tags 라는 것이 있습니다.
HTML을 삭제하고 txt만 남기죠. 그리고 나서 공백이 2개 이상이거나 줄바꿈이 필요 없거나 탭 같은것은 별도 삭제를 해줘야 합니다.
여기서 다루는 함수는 자바스크립트등 몇가지를 더 삭제해 주는 기능입니다.
결과 확인 후 본인에게 맞지 않으면 좀 더 추가 해야 될 수 있는데 요즘은 GPT4 이용하면 도움이 많이 됩니다.
/**
* html2txt
*
* @param mixed $document
* @return string|string[]|null
*/
function strip_tags_html2txt($document) {
$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
);
$text = preg_replace($search, '', $document);
return $text;
}