I have a string like "My String 2" and I like to get only num value "2". I try to do that you see below but result is egal to 0.
$AlphaSURV1="My String 2";
$NumSURV1=intval($AlphaSURV1);
echo $NumSURV1;
Can you help me to solve that?
Thanks
In order to capture the last group of digits in a string, you can use a regular expression:
$str = "123 test 29";
preg_match("/[0-9]+$/", $str, $matches);
var_dump($matches[0]); # 29
This work correctly for all the following cases, including lack of whitespace, leading digits and multiple digits at the end of the string:
"1" => 1
"test 2" => 2
"test 34" => 34
"5 test 6" => 6
"7test8" => 8
Note that if you simply want to get the last character in the string and treat it like a number you can use the following:
$str = "My String 2";
$digit = intval(substr($str, -1));
You can strip out the non-numeric characters with a regular expression which matches non-digits:
$NumSURV1 = preg_replace("/[^0-9]/", "", $AlphaSURV1);
Well, your comment on your original post makes this answer kind of invalid. If you put "3 some text 5"
into the preg_replace()
answer I gave, you'll get "35"
, not just "5"
. If I take a wild guess and assume you just want the last chunk of text out of the string instead of all the numbers, and assuming there are spaces, you should do this:
$exp = explode(" ", $AlphaSURV1);
$NumSURV1 = $exp[count($exp) - 1];
Which is ugly, but it will split your input string on spaces and give you the last element in the resulting array.
A prettier way of doing the second answer, thanks to @nickb:
$exp = explode(" ", $AlphaSURV1);
$NumSURV1 = end($exp);
(incidentally, you could do $NumSURV1 = end(explode(" ", $AlphaSURV1));
as it works, but you'll get a Strict Standards: Only variables should be passed by reference
error if you have strict checking enabled on your server)