2

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

$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>';

如何从字符串中提取每个区域的坐标、地点和时间?

4

2 回答 2

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
于 2012-11-29T13:07:42.417 回答
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——除非你当然期待时代的结束

看看在解析标记时如何让你的生活更轻松,这就是文档的用途。

正如@SalamanA 指出的那样,将片段视为整个 DOM 可能被认为是矫枉过正。值得庆幸的是,在这种情况下可以使用诸如DOMFragment 类之类的东西。

$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);
于 2012-11-29T13:13:59.630 回答