RegEx空白减少+ Textarea排除

时间:2012-09-03 15:03:05

标签: html regex textarea

我正在使用/\s+/将所有空格字符缩减为一个(在每个组中)。这目前用于缩小HTML,但textareas需要额外的换行符,否则将被过滤掉。如何修改此正则表达式以忽略<textarea></textarea>标记内的换行符?

此外,textarea可能包含idclass等属性。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

好的,这是PHP中的通用解决方案,希望用你用于此任务的任何语言重写都很容易。

$raw = '
  My   line   is   here <textarea>And 
there</textarea> there   and everywhere';

$chunks = preg_split('#(<textarea>.+?</textarea>)#si', 
  $raw, null, 
  PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); // -- 1

$chunks_length = count($chunks);
for ($index = 0; 
     $index < $chunks_length; 
     $index += 2) { // -- 2
  $chunks[$index] = preg_replace('#(\s)+#', '$1', $chunks[$index]); // -- 3
}

var_dump(implode('', $chunks));
// My line is here <textarea>And 
// there</textarea> there and everywhere

这就是这里发生的事情:使用--1行,我们将您的文本拆分为片段数组。具有奇数索引[1,3,...]的此数组的元素实际上将是“textarea”块,因为我们将preg_split设置为以“分隔符捕获”模式工作。关键是我们不会处理它们(在for循环中踩过它们),并且只会压缩“内容”元素的空白(--3)。

然而,正如Rob W所正确提到的那样,这种方法非常脆弱:并非HTML中的所有空格都可以轻松压缩。

P.S。正则表达式中的s修饰符用于某个原因;否则.+?模式将无法捕获结束\n符号(阻止正确捕获多行块)。

答案 1 :(得分:0)

使用带有大小写不敏感修饰符的正则表达式模式/(?:\s+(?![^<]*<\/textarea>)|[^\S\n\r]+)/

相关问题