Remove non-numeric characters (excluding periods and commas) from a string (i.e. remove all characters except numbers, commas, and periods) Ask Question

Remove non-numeric characters (excluding periods and commas) from a string (i.e. remove all characters except numbers, commas, and periods) Ask Question

If I have the following values:

 $var1 = AR3,373.31

 $var2 = 12.322,11T

How can I create a new variable and set it to a copy of the data that has any non-numeric characters removed, with the exception of commas and periods? The values above would return the following results:

 $var1_copy = 3,373.31

 $var2_copy = 12.322,11

ベストアンサー1

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

おすすめ記事