Search code examples
phpregex

Remove all non-alphanumeric characters but keep float values


I have the following to strip a string to alphanumeric a-z0-9:

echo preg_replace("/[^[:alnum:][:space:]]/u", '', $text);

Works fine. How do I allow it to keep floats, so 10.9 is not stripped to 109. I tried /[^[:alnum:][:space:][.]]/u but didn't work.

It should not strip floats, but should strip dots if it isn't a decimal number. So etc. should be stripped to etc, but 1.5 should stay as 1.5.


Solution

  • You can use look-around for checking whether there is no digit before the dot, or there is no digit after it, and only then delete it:

    echo preg_replace("/[^[:alnum:][:space:].]|(?<!\d)\.|\.(?!\d)/u", '', $text);