Method 1: The regular expression '/[\W]/' matches all the non-alphanumeric characters and replace them with ' ' (empty string). $str = preg_replace( '/[\W]/', '', $str);
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 (” “).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With