PHP - remove all non-numeric characters from a string

PhpString

Php Problem Overview


What is the best way for me to do this? Should I use regex or is there another in-built PHP function I can use?

For example, I'd want: 12 months to become 12. Every 6 months to become 6, 1M to become 1, etc.

Php Solutions


Solution 1 - Php

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

Solution 2 - Php

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionb85411View Question on Stackoverflow
Solution 1 - PhppguetschowView Answer on Stackoverflow
Solution 2 - PhpAvinash RajView Answer on Stackoverflow