Get all matches from string that start with and end, using php

user1935281 picture user1935281 · Jan 13, 2013 · Viewed 21.5k times · Source

How would I use PHP to extract everything in between [startstring] and [endstring] from this string:

[startstring]hello = guys[endstring] hello guys [startstring]jerk = you[endstring] welcome to the universe

I'd like to find all the matches of [startstring] and [endstring], and echo the text inside. Kinda like a delimiter. And I would like all the matches echoed to be seperated by a space.

How would I go about accomplishing this? Would this require regex? Could you provide a sample?

Thanks so much! :)

Answer

Jeroen picture Jeroen · Jan 13, 2013
preg_match_all('/\[startstring\](.*?)\[endstring\]/s', $input, $matches);
echo implode(' ', $matches);

preg_match_all('/\[startstring\](.*?)\=(.*?)\[endstring\]/s', $input, $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
    $key = $matches[1][$i];
    $value = $matches[2][$i];
    $$key = $value;
}