这可以用正则表达式完成,我认为在这种情况下,DOM不是最简单的方法。 php的一个例子:
$pattern = '~(?>]*+>(?>\s++| )*\1>|
| |\s++)+$~i';
$result = preg_replace($pattern, '', $text);
说明:
~
(?> # open an atomic group
]*+> # opening tags, note that this subpattern allows
# attributes with [^>]*+ you can remove it if you
# don't need it
(?>\s++| )* # content allowed inside the tags *
\1> # closing tag (refer to the first capturing group)
| # OR
# stand alone tag
| # OR
#
| # OR
\s++ # white characters
)+$
~i
(*)请注意,此模式不处理嵌套标记,如:
$pattern = '~(]*+>(?1)*\2>|
| |\s++)+$~i';
此处(?1)指的是第一个捕获组。