删除 php 字符串中的两个以上 returns 和一个以上 space
Remove more than two returns and more than one space within php string
我设法删除了空格,但我不明白为什么它也会删除我的 returns。我的表单中有一个文本区域,我希望最多允许两个 returns。这是我到目前为止一直在使用的。
$string = preg_replace('/\s\s+/', ' ', $string); // supposed to remove more than one consecutive space - but also deletes my returns ...
$string = preg_replace('/\n\n\n+/', '\n\n', $string); // using this one by itself does not do as expected and removes all returns ...
似乎第一行已经去掉了多个空格和所有 returns ... 这很奇怪。不确定我是否做对了...
因为\s
也会匹配换行符。所以我建议你使用 \h
来匹配任何类型的水平空间。
$string = preg_replace('/\h\h+/', ' ', $string);
\s match any white space character [\r\n\t\f ]
参见\s
的定义。它包括\n
。使用
\h matches any horizontal whitespace character (equal to [[:blank:]])
对水平空格使用 \h
。
对于那些需要它的人,这就是从文本区域中删除两个马车 returns 的方法。
preg_replace('/\n\r(\n\r)+/', "\n\r", $str);
对于 space 问题,如上文所述,将 \s 替换为 \h
我设法删除了空格,但我不明白为什么它也会删除我的 returns。我的表单中有一个文本区域,我希望最多允许两个 returns。这是我到目前为止一直在使用的。
$string = preg_replace('/\s\s+/', ' ', $string); // supposed to remove more than one consecutive space - but also deletes my returns ...
$string = preg_replace('/\n\n\n+/', '\n\n', $string); // using this one by itself does not do as expected and removes all returns ...
似乎第一行已经去掉了多个空格和所有 returns ... 这很奇怪。不确定我是否做对了...
因为\s
也会匹配换行符。所以我建议你使用 \h
来匹配任何类型的水平空间。
$string = preg_replace('/\h\h+/', ' ', $string);
\s match any white space character [\r\n\t\f ]
参见\s
的定义。它包括\n
。使用
\h matches any horizontal whitespace character (equal to [[:blank:]])
对水平空格使用 \h
。
对于那些需要它的人,这就是从文本区域中删除两个马车 returns 的方法。
preg_replace('/\n\r(\n\r)+/', "\n\r", $str);
对于 space 问题,如上文所述,将 \s 替换为 \h