Jump to content

I hate preg_match!


Rifts

Recommended Posts

why doesnt this work

 

function getTextBetweenTags($string, $start, $end)
{
    $pattern = "/$start(.*?)$end/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$html = 'this is a bunch of nothing _MARKER_OBJ = [ get this crap ]';

$content = getTextBetweenTags($html, '_MARKER_OBJ = [', ']');

echo $content;

 

it just returns nothing, if I change the start to just _MARKER_OBJ it works though

Link to comment
https://forums.phpfreaks.com/topic/254505-i-hate-preg_match/#findComment-1304984
Share on other sites

If you're wanting to restrict it to just text either side as the "tags" you could use

function getTextBetweenTags($string, $start, $end) {
$start = preg_quote($start, '~');
$end = preg_quote($end, '~');
$pattern = "~$start(.*?)$end~";

if(preg_match($pattern, $string, $matches)) {
	return $matches[1];
}

return false;
}

$html = 'this is a bunch of nothing _MARKER_OBJ = [ get this crap ]';

$content = getTextBetweenTags($html, '_MARKER_OBJ = [', ']');

echo $content;

 

That doesn't require you to escape the start/end tags as it escapes all regex syntax characters using preg_quote

Link to comment
https://forums.phpfreaks.com/topic/254505-i-hate-preg_match/#findComment-1305021
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.