Skip to content
Advertisement

Preg_match string inside curly braces tags

I’d like to grab a string between tags. My tags will be with curly braces.

{myTag}Here is the string{/myTag}

So far I have found #<s*?$tagnameb[^>]*>(.*?)</$tagnameb[^>]*>#s This one matches tags with angle brackets <>. I couldn’t figure out how to make it look for curly braces.

Eventually I would like to parse whole page and grab all matches and build an array with strings.

This is the code:

function everything_in_tags($string, $tagname)
{
    $pattern = "#<s*?$tagnameb[^>]*>(.*?)</$tagnameb[^>]*>#s";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$var = everything_in_tags($string, $tagname);

Advertisement

Answer

Replace all occurrences of < and > with { and } and change preg_match() to preg_match_all()` to catch multiple occurrences of text inside those tags.

function everything_in_tags($string, $tagname)
{
    $pattern = "#{s*?$tagnameb[^}]*}(.*?){/$tagnameb[^}]*}#s";
    preg_match_all($pattern, $string, $matches);
    return $matches[1];
}


$string = '{myTag}Here is the string{/myTag} and {myTag}here is more{/myTag}';
$tagname = 'myTag';
$var = everything_in_tags($string, $tagname);

Forget about what I mentioned about escaping the curly brackets – I was mistaken.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement