简体   繁体   English

创建一个Javascript RegExp以在HTML / php模板中查找开始标记

[英]Create a Javascript RegExp to find opening tags in HTML/php template

I'm trying to write a Javascript HTML/php parser which would extract all opening tags from a HTML/php source and return the type of tag and attributes with their values while at the same time monitoring whether the values/attributes should be evaluated from static text or php variables. 我正在尝试编写一个Javascript HTML / php解析器,它将从HTML / php源中提取所有开始标记,并返回标记和属性的类型及其值,同时监视是否应评估值/属性静态文本或php变量。 The problem is when I try to compose the Javascript RegExp pattern and more specifically certain rare cases. 问题是当我尝试编写Javascript RegExp模式时,更具体地说是某些罕见情况。 The RegExp I was able to come up with either involve negative lookbehind (to cope with the closing php tag - that is to match a closing bracket that is not preceded by a question mark) or fails in certain cases. RegExp我能够提出任何涉及负面的lookbehind(以处理关闭的php标记 - 即匹配一个没有问号的结束括号)或在某些情况下失败。 The lookbehind version looks like: lookbehind版本看起来像:

<[a-zA-Z]+.*?(?<!\?)>

...and works perfect except for my case which must avoid using lookbehind. ...除了我必须避免使用lookbehind的情况外,它的工作原理很完美。 A more Javascript friendly version would be: 更友好的Javascript版本是:

<[a-zA-Z]+((.(?!</)(?!<[a-zA-Z]+))*)?>

...which works except in this case: ......在这种情况下除外:

<option value="<?php echo $img; ?>"<?php echo ($hpb[$i]['image_filename']==$img?' selected="selected"':''); ?>><?php echo $img; ?></option>

Am I approaching the problem completely messed up or is the lookbehind really necessary in my case? 我是否完全搞砸了这个问题,或者在我的情况下真的有必要吗? Any help is greatly appreciated. 任何帮助是极大的赞赏。

Just make sure the last letter before the '>' is not a ?, using [^?]. 只需确保'>'之前的最后一个字母不是?,使用[^?]。 No lookaheads or -behinds needed. 不需要前瞻或后顾之忧。

<[a-zA-Z](.*?[^?])?>

the parentheses and the last ? 括号和最后? is to also match tags like <b> . 也是为了匹配像<b>这样的标签。

EDIT The solution didn't work for single character tags without attributes. 编辑该解决方案不适用于没有属性的单个字符标签。 So here is one that does: 所以这是一个做的:

<[a-zA-Z]+(>|.*?[^?]>)

更简单的答案是<[^ / ^>] +>

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

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