Regex trim or preg_replace white space including tabs and new lines

寵の児 提交于 2019-12-01 11:12:11

问题


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>


回答1:


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>"



回答2:


$str = trim($str, "\t\n");

See trim




回答3:


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.




回答4:


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>)$)



回答5:


@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);      
  ?>


来源:https://stackoverflow.com/questions/9129368/regex-trim-or-preg-replace-white-space-including-tabs-and-new-lines

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