Get content between two strings PHP
You may as well use substr and strpos for this.
$startsAt = strpos($out, "{FINDME}") + strlen("{FINDME}");$endsAt = strpos($out, "{/FINDME}", $startsAt);$result = substr($out, $startsAt, $endsAt - $startsAt);
You'll need to add error checking to handle the case where it doesn't FINDME.
- Use
#
instead of/
so you dont have to escape them. - The modifier
s
makes.
and\s
also include newlines. {
and}
has various functionality like from n to m times in{n,m}
.The basic
preg_match('#\\{FINDME\\}(.+)\\{/FINDME\\}#s',$out,$matches);
The advanced for various tags etc (styling is not so nice by the javascript).
$delimiter = '#';$startTag = '{FINDME}';$endTag = '{/FINDME}';$regex = $delimiter . preg_quote($startTag, $delimiter) . '(.*?)' . preg_quote($endTag, $delimiter) . $delimiter . 's';preg_match($regex,$out,$matches);
Put this code in a function
- For any file which you do not want to execue any stray php code, you should use file_get_contents. include/require should not even be an option there.
I like to avoid using regex if possible, here is alternative solution to fetch all strings between two strings and returns an array.
function getBetween($content, $start, $end) { $n = explode($start, $content); $result = Array(); foreach ($n as $val) { $pos = strpos($val, $end); if ($pos !== false) { $result[] = substr($val, 0, $pos); } } return $result;}print_r(getBetween("The quick brown {{fox}} jumps over the lazy {{dog}}", "{{", "}}"));
Results :
Array( [0] => fox [1] => dog)