简体   繁体   English

php Pattern匹配自定义标签

[英]php Pattern Matching for custom tags

I am trying to replace all the tags in a file like {{name:something}} to some certain values. 我正在尝试将{{name:something}}等文件中的所有标记替换为某些特定值。 Note that in {{name::something}} only something might warry. 请注意,在{{name::something}}只有某些内容可能会有所不同。 Like {{name:title}} or {{name:content}} . 例如{{name:title}}{{name:content}} That "name" will always be there. 那个“名字”将永远存在。

Anyway, I used preg_match_all and preg_replace, it all worked out. 无论如何,我使用了preg_match_all和preg_replace,一切都解决了。 I found the matches with this regular expression: $patmatch="/{{name:[a-zA-Z0-9._-]+}}/"; 我找到了这个正则表达式的匹配项: $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. 当像这样的标记与模式(它有语法错误)不匹配时,如{{notname:something}}{{name something}}{{ }}我必须抛出异常。 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}} ? 我可以以某种方式进行另一种模式搜索,以检查它是否是一个标记( {{}} ),如果它不像{{name:something}}

Any help would be appreciated, Thanks! 任何帮助将不胜感激,谢谢!

Off the top of my head: 脱离我的头顶:

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

Something like that? 那样的东西?

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: 假设您有包含文件内容的$ content变量,您可以临时存储验证数据,如下所示:

$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

也许你可以使用像subpattern,命名和检查结果的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM