Regex trim or preg_replace white space including tabs and new lines

天大地大妈咪最大 提交于 2019-12-01 13:49:24

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>"
$str = trim($str, "\t\n");

See trim

preg_* functions provides whitespace escape sequence \s, which you can use, so you're regex would be:

$regexp = '~...>\\s*([^<]*?)\\s*<~m'

Maybe you will need to use [\\s$] instead of just \\s, I'm nor sure how PCRE handles newlines in those cases.

I only want to trim the whitespace immediately after <code><div class="b-line"></div> and immediately before </code>

Can be done with:

preg_replace(',(?|(<code><div class="b-line"></div>)\s+|\s+(</code>)),', '$1', $str);

Example here.


If the <code> tag only occurs at beginning/end of string you would want to anchor the expression with ^ and $:

(?|^(<code><div class="b-line"></div>)\s+|\s+(</code>)$)

@Vyktor's answer is almost correct. If you just run echo preg_replace('/\s/', '', $s); against your string (which is $s) you will get:

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

Test snippet:

  <?php
  $s = <<<EOF
  <code><div class="b-line"></div>




      poo
  <lol>
   n

  </code>      
  EOF;      
  echo preg_replace('/\s/', '', $s);      
  ?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!