Search code examples
phpnumbers

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


Solution

  • $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.