Darksody
Darksody

Reputation: 379

php Pattern Matching for custom tags

I am trying to replace all the tags in a file like {{name:something}} to some certain values. Note that in {{name::something}} only something might warry. Like {{name:title}} or {{name:content}}. That "name" will always be there.

Anyway, I used preg_match_all and preg_replace, it all worked out. I found the matches with this regular expression: $patmatch="/{{name:[a-zA-Z0-9._-]+}}/";

My problem is the following:

When a tag like this does not match the pattern (it has a syntax error), like {{notname:something}} or {{name something}} or {{ }} i must throw an exception. How do i know if the tag is there, but with a syntax error?

Can i somehow make another pattern search to check if it's a tag (between {{ and }}) and if it's not like {{name:something}}?

Any help would be appreciated, Thanks!

Upvotes: 0

Views: 259

Answers (3)

Kyborek
Kyborek

Reputation: 1511

Other answers only check if that tag is inside content, this one checks for true validity:

Assuming that you have $content variable that holds contents of file, you can temporarily store validation data which will be like that:

$validation = preg_replace("/{{name:[a-zA-Z0-9._-]+}}/","",$content);

So you will have cotents stripped off valid tags and now you want to look for invalid tag, depending on how strict you want it, you can use one of theese:

if(preg_match('/{{name:[^}]*}}/', $validation)) //found error tag
//alternatively you might want to check for typos like "nmae":
if(preg_match('/{{[^}]*}}/', $validation)) //found error tag

Upvotes: 1

user1291573
user1291573

Reputation: 1

Maybe you can use something like subpattern, naming and check the result

Upvotes: 0

NFLineast
NFLineast

Reputation: 33

Off the top of my head:

if(strpos($text, '{{name:') === false)
{
    //exception
}
else
{
    //properly formatted text
}

Something like that?

Upvotes: 1

Related Questions