2

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"?

devirkahan
  • 430
  • 1
  • 8
  • 22

4 Answers4

3

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

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

Starx
  • 77,474
  • 47
  • 185
  • 261
1

If your number is always on the first and following characters you can use functions like floatval or intval.

Voitcus
  • 4,463
  • 4
  • 24
  • 40
-1

Did you simply try to cast?

echo (int) trim("• 94% positive ·", "•  ·");
echo (int) trim("• 94% positive", "•  ·");

Both should output to:

94

Kind regards...

Jens Peters
  • 2,075
  • 1
  • 22
  • 30