PHP怎么样去掉从word直接粘贴过来的没有用的格式
通常我们会遇到直接把word内的内容,直接粘贴到文本编辑器中。这时候会出现在文本编辑器中有一些word内的没用的标签内容。一般处理的方式有二种:1.通过编辑器的JS直接去除。2.提交到后台后,直接用程序去掉无效标签。下面我就分享一个通过PHP的处理方式,成功率可能不是100%。这程序也是在PHP官网上看到的,就顺便粘贴过来了。
1 function ClearHtml($content,$allowtags='') { 2 3 mb_regex_encoding('UTF-8'); 4 //replace MS special characters first 5 $search = array('/‘/u', '/’/u', '/“/u', '/”/u', '/—/u'); 6 $replace = array('\'', '\'', '"', '"', '-'); 7 $content = preg_replace($search, $replace, $content); 8 //make sure _all_ html entities are converted to the plain ascii equivalents - it appears 9 //in some MS headers, some html entities are encoded and some aren't 10 $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8'); 11 //try to strip out any C style comments first, since these, embedded in html comments, seem to 12 //prevent strip_tags from removing html comments (MS Word introduced combination) 13 if(mb_stripos($content, '#s', '', $content, 'm'); 15 } 16 //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be 17 //'<1' becomes '< 1'(note: somewhat application specific) 18 $content = preg_replace(array('/<([0-9]+)/'), array('< $1'), $content); 19 20 $content = strip_tags($content, $allowtags); 21 //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one 22 $content = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $content); 23 //strip out inline css and simplify style tags 24 $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#]*>(.*?)#isu'); 25 $replace = array('$2', '$2', '$1'); 26 $content = preg_replace($search, $replace, $content); 27 28 //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears 29 //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains 30 //some MS Style Definitions - this last bit gets rid of any leftover comments */ 31 $num_matches = preg_match_all("/\
class
=
"p0"
style=
"text-indent: 24.0000pt; margin-bottom: 0pt;
margin-top: 0pt;"
>
"mso-spacerun:
"
yes
"; font-size: 12.0000pt; font-family:
"
宋体
";"
>《优伴户外旅行》——让旅行成为习惯!
echo
ClearHtml(
$content
,
'
'
);
?>