如何使用 preg_match 提取自定义标签
我使用这个模式 '/(\{(\w+)\}(.*))?\{%(\w+)%\}((.*)\{\/(\w+)\}) ?/i'
使用 preg_match
函数从模板中提取标签。
示例模板:
<table id="middle" cellspacing="0px" cellpadding="0px">
{middle}
<tr>
{left}<td>{%left%}</td>{/left}
<td>{%middle%}{%content%}</td>
{right}<td>{%right%}</td>{/right}
</tr>
{/middle}
</table>
如何确保每个标签的start
和end
与其名称真正匹配
在此示例中,middle
标记同时匹配 middle
和 content
,而它应该只匹配 middle
标记
i use this pattern '/(\{(\w+)\}(.*))?\{%(\w+)%\}((.*)\{\/(\w+)\})?/i'
to extract tags from a template using preg_match
function.
sample template:
<table id="middle" cellspacing="0px" cellpadding="0px">
{middle}
<tr>
{left}<td>{%left%}</td>{/left}
<td>{%middle%}{%content%}</td>
{right}<td>{%right%}</td>{/right}
</tr>
{/middle}
</table>
how to make sure that start
and end
of each tag truly match it's name
in this example middle
tag matches for both middle
and content
while it should just match middle
tag
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为解决这个问题的最佳方法是分几个不同的步骤来完成。
首先,您应该将 preg_replace_callback 与
一起使用/(?>{([^}]+)})(.*)?{\/\1}/sim
作为正则表达式。这将找到顶级 {tag}{/tag}。 $matches[2] 将包含内容(不带标签),而 $matches1 将包含标签本身。您应该创建一个递归调用的函数,以便在回调中,在 $matches[2] 上再次调用它,以便找到子项 {tags} 以防万一有更多。这就是你穿过树的方式。
最后,您应该创建第三个函数来处理 {%tag%}。我将再次使用 preg_replace_callback 并使用 switch 语句来处理标签名称。
这应该为您指明正确的方向。
编辑:这是我上面描述的功能齐全的演示:\
结果字符串将是:
I like Francois Deschenes a lot< /b>.
。
I think the best way to solve this problem would be do this in a few different steps.
First, you should use preg_replace_callback with
/(?>{([^}]+)})(.*)?{\/\1}/sim
as your regular expression. This will find the top level {tag}{/tag}. The $matches[2] will contain the content (without the tags) while $matches1 will contain the tag itself.You should create a function that's called recursively so that in the callback, it's called again on $matches[2] so find the children {tags} just in case there are more. This is how you'll go through the tree.
Finally, you should make a third function that handles the {%tag%}. I would use preg_replace_callback again and make use of the switch statement to handle the tag name.
This should point you in the right direction.
EDIT: Here is a fully functional demo of what I described above:\
The resulting string will be:
<div><p>I like Francois Deschenes a <b>lot</b>.</p></div>
.1我确信(但不确定)要确保封闭标记 ({this}{/this}) 与数据标记 ({%this%}) 匹配,您需要附带 if 语句来测试返回的字符串。
我将使用 preg_replace_callback 函数,如下所示:
preg_replace_callback 函数将作为数组找到的任何匹配项发送到指定的函数进行处理,然后从该函数返回新的格式化字符串。
1I'm confident, but not certain, that to make sure the enclosing tags({this}{/this}) match the data tags ({%this%}), you would need an accompanying if statement to test the returned strings.
I would use the preg_replace_callback function, like so:
the preg_replace_callback function sends any matches found as an array to the specified function for processing, then you return the new formatted string from that function.