| ||||||
|
How to extract a number from a string in PHP using preg_replace()
Sometimes all you need from a string are certain elements. Such an element can be a hidden number which has significance to you. Maybe a timestamp for instance. Here then is how you can lift various numbers from a string using preg_replace() and a well defined regular expression. First let us have a look at the regular expression itself. It has a negative quality thanks to the [^, meaning it is looking for anything that is not a number. The \d stands for decimal, while the \s stands for whitespaces, therefore all the gaps inside the string will be maintained. /[^\d\s] / For no gaps to remain between the numbers simply remove the \s: /[^\d] / Now that we have discussed the regular expression itself we can move on to the preg_replace() and the rest of the code. Notice how we have a string with numerous numerical values inside it. They will all first be removed, then we will echo the string: <?php $string = "The Cavs won 99:98 against the 76ers thanks to #23!"; $string = preg_replace('/[^\d\s] /', '', $string); echo $string; ?>
|