views:

381

answers:

3

Whats is the best way to obtain the content between two strings e.g.

ob_start();
include('externalfile.html'); ## see below
$out = ob_get_contents();
ob_end_clean();

preg_match('/{FINDME}(.|\n*)+{\/FINDME}/',$out,$matches);
$match = $matches[0];

echo $match;

## I have used .|\n* as it needs to check for new lines. Is this correct?

## externalfile.html

{FINDME}
Text Here
{/FINDME}

For some reason this appears to work on one place in my code and not another. Am I going about this in the right way? Or is there a better way?

Also is output buffer the way to do this or file_get_contents?

Thanks in advance!

+2  A: 

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.

Adam Wright
This is the best way of doing it when it is possible
Cem Kalyoncu
+2  A: 
  • 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.
OIS
I bet {FINDME} is just for illustration
Cem Kalyoncu
A: 

Line breaks can cause problems in RegEx, try removing or replacing them with \n before processing.

Cem Kalyoncu