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

2

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

Sequela answered 13/1, 2013 at 21:6 Comment(0)
T
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;
}
Twedy answered 13/1, 2013 at 21:8 Comment(1)
In $hello and $jerk, just like you said. Just run it, echo the variables and try it out!Twedy
T
4

Try with preg_match_all:

preg_match_all('/\[startstring\](.*?)\[endstring\]/', $input, $matches);
var_dump($matches);
Trend answered 13/1, 2013 at 21:8 Comment(6)
(.*?) means a lot of backtracking, but it's by far the simplest method and will be fine. Hope the string isn't huge ;-)Aboveground
@DoubleGras It is going to be huge... :( What do you recommend?Sequela
How would I go about making each match into a variable? Like making hello = guys a real, useable variable in my script? $hello = guysSequela
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.Aboveground
@DoubleGras no, I mean huge. Like I'm doing a whole document. Would it still be speedy? or what? thanks for your helpSequela
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].Aboveground

© 2022 - 2024 — McMap. All rights reserved.