dotty
dotty

Reputation: 41473

stripping out all characters from a string, leaving numbers

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

Answers (5)

Don
Don

Reputation: 4673

$str = preg_replace('/[^0-9.]+/', '', $str);

replace substrings that do not consist of digits or . with nothing.

Here's how it works:

  1. preg_replace is a PHP function that searches a string for a pattern and replaces it with a given replacement string.
  2. The first parameter in 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.].
  3. The second parameter in 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.
  4. The third parameter in 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

Oleksii Kuznietsov
Oleksii Kuznietsov

Reputation: 719

Here is the shortest one:

$str = preg_replace('/\D/', '', $str);

\D = all non-digits.

Upvotes: 4

Juraj Blahunka
Juraj Blahunka

Reputation: 18533

$input = 'some str1ng 234';
$newString = preg_replace("/[^0-9.]/", '', $input);

Upvotes: 2

Veger
Veger

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

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179159

preg_replace('/[^0-9.]/', '', $string);

Upvotes: 7

Related Questions