Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content between two strings PHP

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!

like image 933
Lizard Avatar asked Sep 18 '09 16:09

Lizard


People also ask

How to get value between two strings in php?

Syntax: $arr=explode(separator, string). This will return an array which will contain the string split on the basis of the separator. Split the list on the basis of the starting word.

How to get a substring between two strings in php?

Here's an example: $string = "foo I wanna a cake foo"; We call the function: $substring = getInnerSubstring($string,"foo"); It returns: " I wanna a cake ".

Is substring in string PHP?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .


1 Answers

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.

like image 154
Adam Wright Avatar answered Sep 28 '22 01:09

Adam Wright