0

I have a string which contains several square brackets. I need to get the values as array separated by the square brackets. My example will make you sense:

$inputString = "['A'|'AA']['B'|'BB']['C'|'CC']";

My objective is to get the array like this:

0=>'A'|'AA'
1=>'B'|'BB'
2=>'C'|'CC'
3
  • It is not clear what you intend the values of your associate array to actually be. What is 'A'|'AA' ? Commented Nov 28, 2018 at 7:03
  • Showing our attempts and where you are having problems both helps in understanding the problem as well as shows you have made some effort. Commented Nov 28, 2018 at 7:17
  • The first A represents an image path and the next AA represents its title. The data is too large. So I use A,B,AA like this. Commented Nov 28, 2018 at 7:21

4 Answers 4

2

Remove first and last brackets, then use explode function.

$inputString = "['A'|'AA']['B'|'BB']['C'|'CC']";
$inputString = rtrim($inputString,"]");
$inputString = ltrim($inputString,"[");
print_r(explode("][", $inputString));
/*Array
(
  [0] => 'A'|'AA'
  [1] => 'B'|'BB'
  [2] => 'C'|'CC'
)*/
Sign up to request clarification or add additional context in comments.

Comments

1

Try using PHP explode function..

$inputString = "['A'|'AA']['B'|'BB']['C'|'CC']";
$inputString=str_replace("["," ",$inputString);
print_r (explode("]",rtrim($inputString,"]")));

Comments

1

Try This

$inputString = "['A'|'AA']['B'|'BB']['C'|'CC']";
$obj = str_replace("]","",str_replace("[","",explode("][", $inputString)));
print_r($obj);

Comments

1

using preg_match_all

$inputString = "['A'|'AA']['B'|'BB']['C'|'CC']";
preg_match_all('#\[(.*?)\]#', $inputString, $array);
print_r($array[1]);

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.