15

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! :)

donohoe
  • 13,867
  • 4
  • 37
  • 59

2 Answers2

19
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;
}
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • In `$hello` and `$jerk`, just like you said. Just run it, echo the variables and try it out! – Jeroen Jan 13 '13 at 21:53
4

Try with preg_match_all:

preg_match_all('/\[startstring\](.*?)\[endstring\]/', $input, $matches);
var_dump($matches);
hsz
  • 148,279
  • 62
  • 259
  • 315
  • `(.*?)` means a lot of backtracking, but it's by far the simplest method and will be fine. Hope the string isn't huge ;-) – Gras Double Jan 13 '13 at 21:20
  • @DoubleGras It is going to be huge... :( What do you recommend? –  Jan 13 '13 at 21:36
  • How would I go about making each match into a variable? Like making `hello = guys` a real, useable variable in my script? `$hello = guys` –  Jan 13 '13 at 21:41
  • I don't think it's as *huge* as I meant ;) Don't worry, optimizing this code is probably the *least* of your concerns, really. About dynamically creating variables as you suggested, forget it: unsecure, crash-prone, etc. – Gras Double Jan 13 '13 at 21:47
  • @DoubleGras no, I mean huge. Like I'm doing a whole document. Would it still be speedy? or what? thanks for your help –  Jan 13 '13 at 21:52
  • You'll just have a bit of backtracking between [startstring] and [endstring], so it's completely acceptable (I'd say almost perfect). Only problem is if your document is malformed (a missing [endstring]). By huge I meant tens of MB's between [startstring] and [endstring]. – Gras Double Jan 13 '13 at 21:59