'hex decimals in preg expression

To replace non-breaking space with a normal space:

preg_replace('/\xA0/u', ' ', $value);

But in a class the hex decimal is already declared in a constant. How to use this constant in the pattern?

const NBSP = "\xA0";

preg_replace('/'.self::NBSP.'/u', ' ', $value);


Solution 1:[1]

You need to escape the backslash:

const NBSP = "\\xA0";

Example (with * char, to be more visible):

class Foo 
{
    const NBSP = "\\xA0";
    
    public function __construct($value)
    {
        var_dump(preg_replace('/' . self::NBSP . '/u', '*', $value));
    }
}

new Foo("foo bar"); // (contain a non-breaking space - Not rendered here)
new Foo("foo\xc2\xa0bar"); // (hexa form)

Output :

string(7) "foo*bar"
string(7) "foo*bar"

demo (3v4l.org)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1