正则表达式修剪或 preg_replace 空格,包括制表符和新行 [英] Regex trim or preg_replace white space including tabs and new lines

查看:59
本文介绍了正则表达式修剪或 preg_replace 空格,包括制表符和新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 将所有空白修剪为便便",然后再修剪所有空白?

我想转这个:

\t\n\n\n \t \n 便便<大声笑>n \n \n \t </code>

对此:

poo<大声笑>n

这部分将始终位于字符串的开头:<code><div class="b-line"></div>

谢谢

对不起,我应该解释一下,上面的全部内容都在一个字符串中,我想在之后立即修剪空白<div class="b-line"></div> 和之前 </code>

解决方案

我认为这个基于前瞻和后瞻的正则表达式对你有用:

$str = <<<EOF<code><div class="b-line"></div>\t\n\n\n \t \n 便便<大声笑>n \n \n \t </code>EOF;$str = preg_replace_callback('#(?<=<code><div class="b-line"></div>)(.*?)(\s*<[^>]*>\s*)(.*?)(?=</code>)#is',create_function('$m','return str_replace(array("\n", "\t", " "), "", $m[1]).$m[2].str_replace(array("\n", "\t"," "), "", $m[3]);'),$str);var_dump ( $str );

输出:

string(51) "

poo<大声笑>n"

How can I use PHP to trim all white space up to "poo" and all white space afterwards?

I would like to turn this:

<code><div class="b-line"></div>  \t 

             \n\n\n \t \n   poo
<lol>
 n \n \n \t </code>

In to this:

<code><div class="b-line"></div>poo 
<lol>
 n</code>

This part will always be at the start of the string: <code><div class="b-line"></div>

Thanks

Edit: Sorry I should explain that the whole of the above is in a string and I only want to trim the whitespace immediately after <code><div class="b-line"></div> and immediately before </code>

解决方案

I think this lookahead and lookbehind based regex will work for you:

$str = <<< EOF
<code><div class="b-line"></div>  \t 

             \n\n\n \t \n   poo
<lol>
 n \n \n \t </code>
EOF;
$str = preg_replace_callback('#(?<=<code><div class="b-line"></div>)(.*?)(\s*<[^>]*>\s*)(.*?)(?=</code>)#is',
       create_function('$m',
       'return str_replace(array("\n", "\t", " "), "", $m[1]).$m[2].str_replace(array("\n", "\t", " "), "", $m[3]);'),
       $str);
var_dump ( $str );

OUTPUT:

string(51) "<code><div class="b-line"></div>poo
<lol>
 n</code>"

这篇关于正则表达式修剪或 preg_replace 空格,包括制表符和新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆