Skip to content
Advertisement

Seperate values from string in between characters in php

I have a string (“$big_string“) in php with is combination of small section of strings(“$string“) like this one "-val1(sec1)-", for eg :

$string1="-val1(sec1)-";
$string2="-val2(sec2)-";
$string3="-val3(sec3)-";
$big_string=$string1.$string2.$string3;

How can I separate values from $big_string to an array-like

the val1.. and so on values are between '-' & '(' and the sec1... and so on values are beteen '(' & ')-'

$array[0][0]="val1";
$array[0][1]="sec1";
$array[1][0]="val2";
$array[1][1]="sec2";
$array[2][0]="val3";
$array[2][1]="sec3";

Edit: I received the $big_string as input, above code is for ref that how $big_string is constructed.

Advertisement

Answer

I like to keep my code simple, using basic PHP functions. Something like this:

$big_string = '-val1(sec1)--val2(sec2)--val3(sec3)-';

$val_sec_array = explode('--', trim($big_string, '-'));
foreach ($val_sec_array as $val_sec) {
    $array[] = [strstr($val_sec, '(', TRUE),
                trim(strstr($val_sec, '('), '()')];
}

print_r($array);

The first line uses trim() to trim off the excess '-' at the begin and end of the $big_string and then explodes the remaining string into an array on each '--' it encounters.

The foreach loop then takes that array and uses strstr to first get the section before the '(' from the string and then the section after the '('. The '(' and ')' are then trimmed off the latter section. The two values then form an array [ ... , ... ] and are stored in the main array.

This is funny, saying it like this makes it sound more complex than it really is. Just look in the manual how this works:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement