我明白了,因为正则表达式本质上是无状态的,要实现复杂的匹配而不诉诸补充应用逻辑是相当困难的,但是我很想知道下面是否可能。正则表达式匹配空白,但跳过部分
匹配所有的空白,很容易:\s+
但跳过某些分隔符之间的空白,在我的情况
字<pre>
和
</pre>
nostrip
。
是否有任何技巧可以实现这个目标?我正在考虑沿着两个单独的比赛,一个为所有空白,一个为
nostrip部分,并以某种方式否定后者从前者。<pre>
块
"This is some text NOSTRIP this is more text NOSTRIP some more text."
// becomes
"ThisissometextNOSTRIP this is more text NOSTRIPsomemoretext."
给出
标签
NOSTRIP部分是无关紧要的,我不会试图解析
的嵌套树
HTML或任何,只是整理一个文本文件,但节省了
nostrip部分中的空格,原因很明显。<pre>
blocks
(更好?)
这是最终我跟去了。我相信它可以在几个地方进行优化,但现在它可以很好地工作。
public function stripWhitespace($html, Array $skipTags = array('pre')){
foreach($skipTags as &$tag){
$tag = "<{$tag}.*?/{$tag}>";
}
$skipped = array();
$buffer = preg_replace_callback('#(?<tag>' . implode('|', $skipTags) . ')#si',
function($match) use(&$skipped){
$skipped[] = $match['tag'];
return "\x1D" . (count($skipped) - 1) . "\x1D";
}, $html
);
$buffer = preg_replace('#\s+#si', ' ', $buffer);
$buffer = preg_replace('#(?:(?<=>)\s|\s(?=<))#si', '', $buffer);
for($i = count($skipped) - 1; $i >= 0; $i--){
$buffer = str_replace("\x1D{$i}\x1D", $skipped[$i], $buffer);
}
return $buffer;
}
你在html上使用正则表达式吗?为什么? – 2011-05-12 20:51:51
实际上,你需要的更加复杂:正则表达式还需要确保在
,反之亦然。 – abesto 2011-05-12 20:54:30http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – mellamokb 2011-05-12 21:02:22