0

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!

3 Answers 3

1

Off the top of my head:

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

Something like that?

Sign up to request clarification or add additional context in comments.

3 Comments

Well, almost. You see, the preg_match_all() function will get me only the right matches. The properly formatted texts. But i need to also find the incorrect ones and throw an exception if i find any.
Thank you all, i solved the problem with NFLineast's ideea. I just preg_match_all() on every $patmatch="/{{[a-zA-Z0-9.:_-]+}}/"; (basically every {{ }} ) and then i just check if(strpos($text, '{{name:') === false) as NFLineast said. Thanks again, all of your solutions are good, i will try the others aswell i think :) Darksody.
Excellent. strpos() is also a lot less resource hungry than preg_match()... :)
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.