Search code examples
phpregexasciitrim

Delete EN space from string on PHP


In one pice of my code detect that rtrim() not delete a space at end of strings.

Investigating, I see that string contain a EN SPACE (U+2002)

$str = 'ANDREWS CAROLE [US]';
// rawurlencode($s) //--> "ANDREWS%20CAROLE%E2%80%82%5BUS%5D"
$pat = "/\[(.*?)\]/";
$str = preg_replace($pat,'',$str); //--> "ANDREWS CAROLE " -> ANDREWS%20CAROLE%E2%80%82"

Try but fail Filter all types of whitespace in PHP

$new = preg_replace('\p{Zs}$', '', $s)

I don't know $character_mask value for this space for use with rtrim


Solution

  • You can use [\p{Z}\t]* before your pattern to match zero or more optional whitespaces including unicode whitespaces:

    $str = 'ANDREWS CAROLE [US]';
    var_dump ( preg_replace('/[\p{Z}\t]*\[(.*?)\]/u', '', $str) );
    //=> string(14) "ANDREWS CAROLE"