Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - remove all non-numeric characters from a string [duplicate]

Tags:

string

php

People also ask

How do I remove all non numeric characters from a string in PHP?

Method 1: The regular expression '/[\W]/' matches all the non-alphanumeric characters and replace them with ' ' (empty string). $str = preg_replace( '/[\W]/', '', $str);

How remove all special characters from a string in PHP?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).

How do I remove a word from a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.


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


Use \D to match non-digit characters.

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