If I have a string like this ,
$my_string="array('red','blue')";
How can I convert this to a real array ?
Example. :
$my_array=array('red','blue');
If I have a string like this ,
$my_string="array('red','blue')";
How can I convert this to a real array ?
Example. :
$my_array=array('red','blue');
DO NOT USE EVAL
. That is terrible overkill and very probably extremely unsafe.
While this is not the BEST way of doing this (as mentioned in question comments), you can use this below function to do exactly what you need.
How it works:
It uses Regex to find and split the string based on these layouts, the array is split using preg_split
which is a regex verson of the more popular explode
.
Once split the array will have some blank values so simply use array_filter
to remove these blank values.
so:
// Explode string based on regex detection of:
//
// (^\h*[a-z]*\h*\(\h*')
// 1) a-z text with spaces around it and then an opening bracket
// ^ denotes the start of the string
// | denotes a regex OR operator.
// \h denotes whitespace, * denotes zero or more times.
//
// ('\h*,\h*')
// 2) or on '),(' with possible spaces around it
//
// ('\h*\)\h*$)
// 3) or on the final trailing '), again with possible spaces.
// $ denotes the end of the string
// the /i denotes case insensitive.
function makeArray($string){
$stringParts = preg_split("/(^\h*[a-z]*\h*\(\h*')|('\h*,\h*')|('\h*\)\h*$)/i",$string);
// now remove empty array values.
$stringParts = array_filter($stringParts);
return $stringParts;
}
Usage:
//input
$myString = " array('red','blue')";
//action
$array = makeArray($myString);
//output
print_r($array);
Output:
Array (
[1] => red
[2] => blue
)
Example 2:
$myString = " array('red','blue','horses', 'crabs (apples)', '(trapdoor)', '<strong>works</strong>', '436')";
$array = makeArray($myString);
print_r($array);
Output:
Array (
[1] => red
[2] => blue
[3] => horses
[4] => crabs (apples)
[5] => (trapdoor)
[6] =><strong>works</strong>
[7] => 436
)
Obviously the regex may need slight tweaking based on your exact circumstances but this is a very good starting point...