1

I have the next strings:

generation_1_2
generation_2_8
generation_3_12

How can I put digits from this strings in variables?

For example:

$digit1[0] is 1.
$digit1[1] is 2.
$digit1[2] is 3.
$digit1[0] is 2.
$digit1[1] is 8.
$digit1[2] is 12.
4
  • 2
    Somehow your "next strings" don't match with your example. Please specify. Commented Sep 15, 2010 at 10:10
  • it should be " $digit1[2] is 3 " thats it Commented Sep 15, 2010 at 10:14
  • and " $digit2[1] is 8 "? Commented Sep 15, 2010 at 10:17
  • This is a very poorly described and presented question. You cannot have duplicate keys on a given level of an array. Is the input one string or three strings? A coding attempt would offer more clarity -- even if that attempt is flawed. Commented Jan 19 at 9:52

3 Answers 3

4
function ret_int($str){
    return array_slice(explode('_', $str), 1);
}
Sign up to request clarification or add additional context in comments.

Comments

4

If you want to extract the trailing numbers you can do:

if(preg_match_all('/(\d+)$/m',$input,$m)){
   // $m[1] will have all the matches.
}

working link

EDIT:

Answer to your edited question to extract both the digits:

$digit = array();
if(preg_match_all('/(\d+)\D*(\d+)$/m',$input,$m)) {
        $digit = array_merge($m[1],$m[2]);
}

Working link

Comments

1

If you just want to extract the digits from the strings, you can explode them like fabrik wrote ($arr = array_slice(explode('_', $str), 1);).

Then using intval, convert each of them to integers like this: $int_a = intval($str_a, 10) where $str_a is one string from the array $arr.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.