Reputation: 41473
Hay, i have a string like this:
v8gn5.8gnr4nggb58gng.g95h58g.n48fn49t.t8t8t57
I want to strip out all the characters leaving just numbers (and .s)
Any ideas how to do this? Is there a function prebuilt?
thanks
Upvotes: 35
Views: 44262
Reputation: 4673
$str = preg_replace('/[^0-9.]+/', '', $str);
replace substrings that do not consist of digits or . with nothing.
Here's how it works:
preg_replace
is a PHP function that searches a string for a pattern and replaces it with a given replacement string.preg_replace
is the regular expression pattern to search for. In this case, the pattern is '/[^0-9.]+/'
, which matches any character that is not a digit or a dot. The ^ character inside square brackets means "not", so [^0-9.]
means any character that is not a digit or a dot. The +
sign means one or more occurrences of the previous character or character group, in this case [^0-9.].preg_replace
is the replacement string. In this case, the replacement string is an empty string ''. So any character that matches the pattern in the first parameter will be replaced with an empty string.preg_replac
is the input string to search and modify. In this case, the input string is represented by the variable $str
.So, this line of code will remove any character from the input string $str that is not a digit or a dot, and return the modified string with only digits and dots.
Upvotes: 96
Reputation: 719
Here is the shortest one:
$str = preg_replace('/\D/', '', $str);
\D = all non-digits.
Upvotes: 4
Reputation: 18533
$input = 'some str1ng 234';
$newString = preg_replace("/[^0-9.]/", '', $input);
Upvotes: 2
Reputation: 37915
To satisfy my curiosity I asked about the speed of the proposed answers and as shown in preg_replace speed optimisation/ it is (much) faster to use str_replace()
than preg_replace()
.
So you might want to use str_replace()
instead.
Upvotes: 0