Home > Backend Development > PHP Tutorial > 正则表达式 xml 取出多个详细的值

正则表达式 xml 取出多个详细的值

WBOY
Release: 2016-06-23 13:26:30
Original
996 people have browsed it

1A0003|B股指数|BGZS|16
1B0001|工业指数|GYZS|16
1B0002|商业指数|SYZS|16
1B0004|地产指数|DCZS|16
1B0005|公用指数|GYZS|16
1B0006|综合指数|ZHZS|16

这是xml的部分值,请问要如何依次取出相应的值?
比如将1A0003、1B0001放在一个数组里,
B股指数、工业指数放在一个数组里,
BGZS、GYZS放在一个数组。

谢谢各位大牛,
preg_match_all使用三次么?
该怎么写这样的表达式?


回复讨论(解决方案)

使用正则捕获功能。

<?php $s = '<PY>1A0003|B股指数|BGZS|16</PY><PY>1B0001|工业指数|GYZS|16</PY><PY>1B0002|商业指数|SYZS|16</PY><PY>1B0004|地产指数|DCZS|16</PY><PY>1B0005|公用指数|GYZS|16</PY><PY>1B0006|综合指数|ZHZS|16</PY>';preg_match_all('/<PY>([^|]*)\|([^|]*)\|([^|]*)\|([^<]*)<\/PY>/', $s, $matches);print_r($matches[1]);print_r($matches[2]);print_r($matches[3]);print_r($matches[4]);
Copy after login


结果:
Array
(
[0] => 1A0003
[1] => 1B0001
[2] => 1B0002
[3] => 1B0004
[4] => 1B0005
[5] => 1B0006
)
Array
(
[0] => B股指数
[1] => 工业指数
[2] => 商业指数
[3] => 地产指数
[4] => 公用指数
[5] => 综合指数
)
Array
(
[0] => BGZS
[1] => GYZS
[2] => SYZS
[3] => DCZS
[4] => GYZS
[5] => ZHZS
)
Array
(
[0] => 16
[1] => 16
[2] => 16
[3] => 16
[4] => 16
[5] => 16
)

$str = <<<EOF<root><PY>1A0003|B股指数|BGZS|16</PY><PY>1B0001|工业指数|GYZS|16</PY><PY>1B0002|商业指数|SYZS|16</PY><PY>1B0004|地产指数|DCZS|16</PY><PY>1B0005|公用指数|GYZS|16</PY><PY>1B0006|综合指数|ZHZS|16</PY></root>EOF;$s = simplexml_load_string($str);foreach($s->xpath("//PY") as $k=>$v){	list($a[],$b[],$c[])=explode('|',$v);}echo "<pre class="brush:php;toolbar:false">";print_r($a);print_r($b);print_r($c);echo "
Copy after login
";/*Array( [0] => 1A0003 [1] => 1B0001 [2] => 1B0002 [3] => 1B0004 [4] => 1B0005 [5] => 1B0006)Array( [0] => B股指数 [1] => 工业指数 [2] => 商业指数 [3] => 地产指数 [4] => 公用指数 [5] => 综合指数)Array( [0] => BGZS [1] => GYZS [2] => SYZS [3] => DCZS [4] => GYZS [5] => ZHZS)*/

谢谢大牛的方法,两种方法都试了,都是可以输出结果的!非常感谢!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template