How to trim string down to content between <!-- MARKER --> and <!-- / MARKER -->

Let’s assume that one had a string variable something like:

$content = “garbage garbage garbage garbage <!-- MARKER –> gold gold gold gold <!-- / MARKER –> garbage garbage garbage garbage”;

What would be the best way to be able to create a variable called $gold that contains only the “gold gold gold gold” content as marked by the opening and closing of the <!-- MARKER –> tag?

I’m having issues getting this small filtering task accomplished, any help would be much appreciated.


Use a regular expression

preg_match(“/<!-- MARKER –>(.*?)<!–\ / MARKER –>/”, $content, $matches);
$gold = $matches[1];

This demo function should do what you want.

The output is a string of the content between the markers.