0

I want to extract multiple substrings from a string and put in an array..

for example:

$string = '{[John][16 years old][New York]}{[Michael][22 years old][Las Vegas]}{[Smith][32 years old][Chicago]}';
$array = ["John,16 years old, New York, Mihael, 22 years old, Las Vegas, Smith, 32 years old, Chicago"];

Someone any ideea?

AsgarAli
  • 2,201
  • 1
  • 20
  • 32
C. Smith
  • 77
  • 1
  • 11
  • 1
    Possible duplicate of [PHP: Split string](http://stackoverflow.com/questions/5159086/php-split-string) – tokamak Feb 08 '16 at 22:00
  • 1
    Is your example correct? The array has one single (string) element? If yes, the question really has nothing to do with arrays – Steve Feb 08 '16 at 22:01
  • 1
    your array consists in one only string element. It is what do you want? – fusion3k Feb 08 '16 at 22:01
  • ... or maybe you intend: [ 'John,16 years old,New York', 'Michael,22 years old,Las Vegas' ... ] – fusion3k Feb 08 '16 at 22:02

3 Answers3

1

A simple preg_match will do it:

$string = '{[John][16 years old][New York]}{[Michael][22 years old][Las Vegas]}{[Smith][32 years old][Chicago]}';
preg_match_all('/\[(.*?)\]/', $string , $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);

/*
Array
(
    [0] => John
    [1] => 16 years old
    [2] => New York
    [3] => Michael
    [4] => 22 years old
    [5] => Las Vegas
    [6] => Smith
    [7] => 32 years old
    [8] => Chicago
)
*/

DEMO:

http://ideone.com/ReaIOr


UPDATE:

To loop all matches you can use:

preg_match_all('/\[(.*?)\]/', $string, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[1]); $i++) {
    echo $matches[1][$i];
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

You appear to be looking to create a single element array, containing a string with certain chars stripped. For this you can use str_replace and trim:

$string = '{[John][16 years old][New York]}{[Michael][22 years old][Las Vegas]}{[Smith][32 years old][Chicago]}';

$cleaned = trim(str_replace(['][', ']}{['],', ', $string), "{}[]");
$array = [$cleaned];
Steve
  • 20,703
  • 5
  • 41
  • 67
1

You'll be spoiled for choice!

This is another answer, if you want extract multiple substrings with name, age, city.

This is simple solution, using substr, explode and str_replace:

$array = array();
foreach( explode( ']}{[', substr( $string,2,-2 )) as $chunk )
{
    $array[] = str_replace( '][', ',', $chunk );
}
print_r( $array );

eval.in demo

Obviously, it works only if there are not curly or squared brackets inside the sigle strings.

First of all, it remove from the original string opening and closing brackets, then explode (transform a string in array) the string by ][ and performs a foreach loop through obtained elements (John][16 years old][New York etc...); for each elements it replace every occurrence of ][ with , and append it to desired array.

That's all

fusion3k
  • 11,568
  • 4
  • 25
  • 47