Regex trim or preg_replace white space including t

2020-03-30 07:00发布

问题:

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


标签: php regex trim