user2312198 user2312198 - 5 months ago 40
PHP Question

Get part of string with PHP

i have this string:

$tree = 'list[0001Red]=null&list[0002Blue]=null&list[0004Sky]=0002Blue&list[0003Green]=null&list[0005Grass]=0003Green';

And I need to get just the first 4 characters that are before the opening bracket, for example.

$tree = '0001,0002,0004,0003,0005';

The four characters are generated randomly so they change.

Thanks for your help

I did it using this code

$tree = explode("list[", $tree);
$pieces = count($tree);
for($x=1; $x < $pieces; $x++){
$temp = substr($tree[$x], 0, 4);
$new_tree = $temp;
$new_tree = $new_tree . "," . $temp;

But the solution of Andreas look better and simple


Use regex

$arr = preg_match_all("/\[(\d{4})/", $tree);

$tree = implode(",", $arr[1]);
echo $tree; //0001,0002,0004,0003,0005