0

I'm not very familiar with php and got stuck in how to use substr in this case:

I have to do the parse of a string that has some numbers and symbols, example:

1[2[3,5],4[7[65,9,11],8]]

And to do this I used a for that will go through and get each char of the string, something like that:

$count = 0;
for($i = 0; $i <= strlen($string); $i++){
    $char = substr($string, $i, 1);
    if($char == '['){
        $count --;
    }
    if($char == ']'){
        $count ++;
    }
    if($count == 0){
        break;
    }

    if(is_numeric(substr($string, $i +1, 1)) and $count == -1){
        $number = substr($string, $i +1, 1);
        $array_aux[] = $number;
    }

}

But as I'm getting the char in (substr ($ string, $ i, 1)) it does not work for numbers with more than one digit, such as 65 and 11

And the contents of the array gets something like: (..., 6, 5, 9, 1, 1, ...)

When should be something like: (..., 65, 9, 11, ...)

Any help?

Sorry, I think was not clear enough. I need the numbers that are inside '[' when count has the value -1

(that's why I'm using substr, and taking every char)

examples: when the string is: 1[2[3,5],4[7[65,9,11],8]], the array must contain 2 and 4

when the string is: 2[3,5],4[7[65,9,11],8]], the array must contain 3 and 5

when the string is: 7[65,9,11],8]], the array must contain 65, 9 and 11. And so on...

Sorry to put these details only now, I was without computer :(

1

2 Answers 2

6

preg_match_all with a simple regular expression can do this for you:

$in = "1[2[3,5],4[7[65,9,11],8]]";
preg_match_all('~\d+~', $in, $out);
print_r($out[0]);

Outputs:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 4
    [5] => 7
    [6] => 65
    [7] => 9
    [8] => 11
    [9] => 8
)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use preg_split and split by matching one or more times not a digit \D+

$str = "1[2[3,5],4[7[65,9,11],8]]";
print_r(preg_split("/\D+/", $str, -1, PREG_SPLIT_NO_EMPTY));

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 4
    [5] => 7
    [6] => 65
    [7] => 9
    [8] => 11
    [9] => 8
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.