我找不到像这样的具体问题所以我发帖了。希望这将是一般用途。
我有一个包含“<w:t> data data.....</w:t>
”XML标记的文件。还有很多其他的东西。我需要捕获<w:t></w:t>
标签内的所有内容(包括)。
我很感激听到有关如何继续的建议。
提前致谢..
大卫
答案 0 :(得分:1)
添加到上一个答案,我会在i之后用小写字母包含's'来处理换行符。
Gumbo先生下面的好点。是的,也可以在's'后面加上大写的'U',使表达式不那么贪婪,否则它将无法按预期工作
e.g。
preg_match_all('/.*& lt; \ / w \:t&gt; / isU',$ string,$ matches);
答案 1 :(得分:1)
您应该使用像SimpleXML这样的XML DOM解析器:
$string = '<?xml version="1.0"?>
<root xmlns:w="http://example.com/">
<w:t>some data...</w:t>
<not-captured>data data</not-captured>
<w:t>more data...</w:t>
</root>';
$doc = simplexml_load_string($string);
foreach ($doc->xpath('//w:t') as $elem) {
var_dump($elem->asXML());
}
如果您没有在XML文档中指定 w 的命名空间,请使用SimpleXMLElement::registerXPathNamespace:
$doc->registerXPathNamespace('w', 'http://example.com/');
答案 2 :(得分:-1)
使用DomXml是首选选项,因为它不会限制您搜索其他标记/数据。
但是使用正则表达式会产生更少的代码,所以如果那些标签只是你需要的东西,我会选择preg_match_all。
$string = '<?xml version="1.0"?>
<root>
<w:t>some data...</w:t>
<not-captured>data data</not-captured>
<w:t>more data...</w:t>
</root>
</xml>';
preg_match_all('/<w\:t>.*<\/w\:t>/is', $string, $matches);
var_dump($matches);
响应:
array(1) {
[0]=>
array(2) {
[0]=>
string(23) "<w:t>some data...</w:t>"
[1]=>
string(23) "<w:t>more data...</w:t>"
}
}
编辑:/是修饰符添加到正则表达式