25
$a = '88';
$b = '88 8888';

echo (int)$a;
echo (int)$b;

as expected, both produce 88. Anyone know if there's a string to int function that will work for $b's value and produce 888888? I've googled around a bit with no luck.

Thanks

2
  • 2
    What int value are you expecting for $b? 888888?
    – Pelshoff
    Commented Aug 10, 2011 at 9:00
  • 1
    PHP does not follow the ISO standard 31-0 when it casts a string to integer. PHP has it's own specification, outlined here: String conversion to numbers.
    – hakre
    Commented Aug 10, 2011 at 9:39

6 Answers 6

40

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);
2
  • 9
    or if you want to remove all non numeric characters (int)preg_replace('#[^0-9]+#', '', $b);
    – Puggan Se
    Commented Aug 10, 2011 at 9:03
  • beware of (int), the maximum supported value is 2147483647, so if you have (int)2222222222 it will return 2147483647 Commented Feb 13, 2019 at 11:54
12

If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).

1

What do you even want the result to be? 888888? If so, just remove the spaces with str_replace, then convert.

1

Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)

intval(str_replace(" ", "", $b))
0

Use str_replace to remove the spaces first ?

0

You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.