Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP code to remove everything but numbers

Tags:

string

regex

php

People also ask

How remove all string from number in PHP?

You can use preg_replace in this case; $res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

How do you delete everything after a character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How can I get only characters in a string in PHP?

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);


Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.


This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

a much more practical way for those who do not want to use regex:

$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);

note: it works with phone numbers too.