107

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
b85411
  • 9,420
  • 15
  • 65
  • 119
  • @mickmackusa Why not [Stripping a phone number of its parenthesis, spaces, and hyphens in PHP?](https://stackoverflow.com/q/5109538/3832970) I do not think this question should be deleted BTW. – Wiktor Stribiżew Dec 27 '21 at 01:09

2 Answers2

238

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,.]/"

Alvarob
  • 79
  • 1
  • 6
pguetschow
  • 5,176
  • 6
  • 32
  • 45
  • Thank you. Out of interest, is it possible to also explode a string with multiple delimiters? So basically allow `explode()` to work on either a comma, a semi-colon, a colon, etc? – b85411 Nov 30 '15 at 08:15
  • hm, take a look here: http://stackoverflow.com/questions/4955433/php-multiple-delimiters-in-explode – pguetschow Nov 30 '15 at 09:06
  • 10
    The provided answer allows the string keep commas and periods. The question asks to remove all non-numeric characters. It's a minor edit (doesn't quite qualify for editing since it's only 2 characters), but the answer to remove all non numeric should be `$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );` – Jon Jun 12 '17 at 03:50
  • Negative numbers * exist * , then $res = preg_replace("/[^0-9.-]/", "", "$ -123.099"); – Hernán Eche Dec 03 '21 at 12:59
76

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274