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).

Answer by Starx

You can use the filter functions to filter the number out.

$yourString =  "• 94% positive";
$int = filter_var($yourString, FILTER_SANITIZE_NUMBER_INT);
echo $int; //WIll echo 94

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!