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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.