C. Smith February 2016

Get multiple substrings from a string in PHP

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?

Answers


Pedro Lobito February 2016

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];
}


Steve February 2016

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];


fusion3k February 2016

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

Post Status

Asked in February 2016
Viewed 1,167 times
Voted 14
Answered 3 times

Search




Leave an answer