从字符串中提取数据

时间:2012-11-29 13:01:40

标签: php string extract explode

我的字符串包含区域地图和其他一些信息:

$string = 'something here 
<map name="map">
< area shape="circle" coords="34,210,3" alt="something 1" href="test.php?place=aaa&time=1" />
< area shape="circle" coords="34,220,3" alt="something2" href="test.php?place=bbb&time=2" />
< area shape="circle" coords="669,229,3" alt="some 8" href="test.php?place=bbb&time=3" />
</map>';

如何从每个区域的字符串中获取坐标,位置和时间?

2 个答案:

答案 0 :(得分:4)

试试这个,我使用正则表达式将变量提取到数组中。您可以使用var_dump查看结果。

$string = 'something here 
<map name="map">
< area shape="circle" coords="34,210,3" alt="something 1" href="test.php?place=aaa&time=1" />
< area shape="circle" coords="34,220,3" alt="something2" href="test.php?place=bbb&time=2" />
< area shape="circle" coords="669,229,3" alt="some 8" href="test.php?place=bbb&time=3" />
</map>';

preg_match_all("/(\d+\,\d+\,\d+)/", $string, $coords);
preg_match_all("/place\=(.*)\&time\=(\d+)/i", $string, $place_time);

var_dump($place_time, $coords);

var_dump()结果

array (size=3)
  0 => 
    array (size=3)
      0 => string 'place=aaa&time=1' (length=16)
      1 => string 'place=bbb&time=2' (length=16)
      2 => string 'place=bbb&time=3' (length=16)
  1 => 
    array (size=3)
      0 => string 'aaa' (length=3)
      1 => string 'bbb' (length=3)
      2 => string 'bbb' (length=3)
  2 => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)

array (size=2)
  0 => 
    array (size=3)
      0 => string '34,210,3' (length=8)
      1 => string '34,220,3' (length=8)
      2 => string '669,229,3' (length=9)
  1 => 
    array (size=3)
      0 => string '34,210,3' (length=8)
      1 => string '34,220,3' (length=8)
      2 => string '669,229,3' (length=9)

您可以通过数组/键访问上述示例中的信息:

echo $coords[1][0]; //return: 34,210,3
echo $place_time[1][0]; //return: aaa
echo $place_time[2][0]; //return: 1

答案 1 :(得分:2)

这看起来像是标记给我,你为什么不简单地解析它?

$DOM = new DOMDocument();
$DOM->loadXML($string);
$areas = $DOM->getElementsByTagName('area');
$coordinates = array();
for ($i = 0, $j = count($areas);$i<$j;$i++)
{
    array_push($areas, $areas[$i]->getAttribute('coords'));
}

这就是你应该对待标记,IMO的方式 - 除非你当然是looking forward to the end of times

See how you can make your life easier when parsing markup,这就是文档的用途。

正如@SalamanA指出的那样,将片段视为整个DOM可能被视为过度杀伤。值得庆幸的是,有DOMFragment class这样的东西可以在这种情况下使用。

$DOMFragment = new DOMDocumentFragment();
$DOMFragment->appendXML($string);
//or, when you need to treat multiple DOMFragments:
$DOM = new DOMDocument();//can be used as a sort-of DOMFragment factory
$fragment = $DOM->createDocumentFragment();
$fragment2 = $DOM->createDocumentFragment();
$fragment->appendXML($string);