非贪婪正则表达式 [英] Non greedy regex
问题描述
我需要在这样的注释php文件中的某些标签内获取值
I need to get the value inside some tags in a comment php file like this
php code
/* this is a comment
!-
<titulo>titulo3</titulo>
<funcion>
<descripcion>esta es la descripcion de la funcion 6</descripcion>
</funcion>
<funcion>
<descripcion>esta es la descripcion de la funcion 7</descripcion>
</funcion>
<otros>
<descripcion>comentario de otros 2a hoja</descripcion>
</otros>
-!
*/
some php code
因此您可以看到该文件包含换行符和<funcion></funcion>
这样的标签的重复,并且我需要获取标签中的每个标签,因此我正在尝试以下操作:
so as you can see the file has newlines and repetions of tags like <funcion></funcion>
and i need to get every single one of the tags, so i was trying something like this:
preg_match_all("/(<funcion>)(.*)(<\/funcion>)/s",$file,$matches);
此示例适用于换行符,但它有点贪婪,因此我一直在搜索并看到以下两种解决方案:
this example works with the newlines but its greedy so i've been searching and seen these two solutions:
preg_match_all("/(<funcion>)(.*?)(<\/funcion>)/s",$file,$matches);
preg_match_all("/(<funcion>)(.*)(<\/funcion>)/sU",$file,$matches);
但是他们都不适合我,不知道为什么
but none of them work for me, don't know why
推荐答案
尝试使用[\s\S]
,它表示所有空格和非空格字符,而不是.
.另外,无需在匹配组中添加<funcion>
和</funcion>
.
Try using [\s\S]
, which means all space and non-space characters, instead of .
. Also, there's no need to add <funcion>
and </funcion>
in match groups.
/<funcion>([\s\S]*?)<\/funcion>/s
此外,请记住,执行此操作的最佳方法是使用 XML解析器.就像您在评论中提到的那样,即使它不是XML文档,也要提取应该解析的部分,然后使用XML解析器对其进行解析.
Also, keep in mind that the best way to do this is parsing the XML using a XML parser. Even if it's not a XML document, as you mentioned on your comment, extract the part that should be parsed and use XML parser to parse it.
这篇关于非贪婪正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!