Home >Backend Development >PHP Tutorial >How to Efficiently Extract Content Between Two Strings in PHP?
Obtaining Content between Two Strings in PHP
The best method to extract content between two strings in PHP depends on specific requirements. Here are two common approaches:
1. Output Buffering
Output buffering stores the output of scripts in a buffer, allowing it to be accessed as a string. This approach is useful if you want to manipulate the output of another script or include external files.
Example:
ob_start(); include('externalfile.html'); $out = ob_get_contents(); ob_end_clean(); preg_match('/{FINDME}(.|\n*)+{\/FINDME}/',$out,$matches); $match = $matches[0]; echo $match;
2. String Manipulation
This approach uses built-in string functions like strpos and substr to search for the starting and ending positions of the desired content.
Example:
$startsAt = strpos($out, "{FINDME}"); $endsAt = strpos($out, "{/FINDME}", $startsAt); $result = substr($out, $startsAt + strlen("{FINDME}"), $endsAt - $startsAt - strlen("{/FINDME}"));
Which Approach to Use?
Additional Notes:
The above is the detailed content of How to Efficiently Extract Content Between Two Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!