manuel mourato
manuel mourato

Reputation: 799

How to separate a string into two, and then make one of those strings into a number [php]

I have this string:

"$string="Med0x2"

What I want, is to separate it into two strings, like this:

$string1="Med0x" ; $string2="2";

And then convert $string2 into an int variable (covert from string to int)

How do I do this?

Upvotes: 0

Views: 42

Answers (3)

Kamehameha
Kamehameha

Reputation: 5473

You can use preg_match for this, using capturing groups to get the parts of the string.
Something like this -

$string = "Med0x2";
$regex = "/^(.*?x)(\d+)$/";
if(preg_match($regex, $string, $matches)){
  $string1 = $matches[1];
  $string2 = $matches[2];
  $integer = intval($string2);
}

Upvotes: 1

Syed Arif Iqbal
Syed Arif Iqbal

Reputation: 1427

you need to Find sub string in first va

$string1 = "Med0x2";
$string2 = (int) substr($string1, -1);
echo "$string2";
echo is_int($string2) ? "yes":"no";

Upvotes: 0

Brian
Brian

Reputation: 903

$string = "Med0x2";
$string1 = substr($string, 0, 5);
$string2 = substr($string, 5);
$integer = (int) $string2;

Upvotes: 2

Related Questions