March 3, 2013
How to strip a string in PHP from everything besides numbers
Question by devirkahan
Currently when I echo
a string I have saved it looks like this:
• 94% positive ·
What I want to have instead is simply:
94
I thought that the following would do the trick:
preg_replace(“/[^0-9]/”,””, $string)
But for some reason (I am assuming the bullet point) doing so instead gives me this:
94018332
Any help to get just the “94”?
Answer by Kolink
You are correct, the bullet point is being handled as an HTML entity and therefore contains numbers.
However, since your format is specific enough, you can use a better regex:
preg_match("/d+(?=%)/",$string,$match);
$percentage = $match[0];
This regex specifically searches for numbers followed immediately by a percent sign (and only the first such match).