php 用正则表达式解析 xml
php parse xml with regular expression
我有 xml 个文件:
<set>
<item>
<id>1</id>
<title>title1</title>
</item>
<item>
<id>2</id>
<title>title2</title>
</item>
<item>
<id>3</id>
<title>title3</title>
<img>img3</img>
</item>
</set>
我只需要解析 "img" 的元素并得到 "id -> img"。我使用正则表达式
preg_match_all('~<item>.*?<id>(.*?)</id>.*?<img>(.*?)</img>.*?</item>~si', $source, $result);
我得到 "id" = '1' and "img" = 'img3', but i need "id" = '3' and "img" = 'img3'
。
请帮我写正则表达式。
不要使用正则表达式解析 html 文件。如果您想使用正则表达式解决方案,那么您可以尝试以下方法。
'~<item>.*?<id>((?:(?!<id>).)*?)</id>(?:(?!<item>).)*<img>(.*?)</img>.*?</item>~si'
(?:(?!<id>).)*?
任何字符的非贪婪匹配但不匹配 <id>
,零次或多次。
我有 xml 个文件:
<set>
<item>
<id>1</id>
<title>title1</title>
</item>
<item>
<id>2</id>
<title>title2</title>
</item>
<item>
<id>3</id>
<title>title3</title>
<img>img3</img>
</item>
</set>
我只需要解析 "img" 的元素并得到 "id -> img"。我使用正则表达式
preg_match_all('~<item>.*?<id>(.*?)</id>.*?<img>(.*?)</img>.*?</item>~si', $source, $result);
我得到 "id" = '1' and "img" = 'img3', but i need "id" = '3' and "img" = 'img3'
。
请帮我写正则表达式。
不要使用正则表达式解析 html 文件。如果您想使用正则表达式解决方案,那么您可以尝试以下方法。
'~<item>.*?<id>((?:(?!<id>).)*?)</id>(?:(?!<item>).)*<img>(.*?)</img>.*?</item>~si'
(?:(?!<id>).)*?
任何字符的非贪婪匹配但不匹配 <id>
,零次或多次。