PHP - 如何使用不同的类名获取span的值

时间:2013-07-01 11:00:55

标签: php arrays

我正在尝试使用不同的类名获取两个span的值并将其放入数组

这是html

$html = '<div class="members">
            <span class="records">Name: </span>
            <span class="values">Marco</span>
        </div>
        <div class="members">
            <span class="records">Mobile: </span>
            <span class="values">+9431109890</span>
        </div>
        <div class="members">
            <span class="records">Age: </span>
            <span class="values">33</span>
        </div>
        <div class="members">
            <span class="records">Sex: </span>
            <span class="values">Male</span>
        </div>'

至于现在我有这个代码

preg_match_all("/\<span class\=\"records\"\>(.*?)\<\/span\>/", $html, $records);
preg_match_all("/\<span class\=\"values\"\>(.*?)\<\/span\>/", $html, $values);
$valueresult = implode("\n", $records[1]); 
$recordresult = implode("\n", $values[1]); 

我不知道如何把它放在数组中 或者如果你有更好的coeds将它放在数组中。

结果必须是

  array(
    'Name'  => 'Marco',
    'Mobile' => '+000000000',
    'Age' => '33',
    'Sex' => 'Male,
  )

2 个答案:

答案 0 :(得分:0)

我不是正则表达式大师,但我修改了它以剥离:标志:

preg_match_all("/\<span class\=\"records\"\>(.*?):(.*?)\<\/span\>/", $html, $records);
preg_match_all("/\<span class\=\"values\"\>(.*?)\<\/span\>/", $html, $values);

$combined = array_combine($records[1], $values[1]);

print_r($combined);

答案 1 :(得分:0)

preg_match_all("/\<span class\=\"records\"\>(.*?)\<\/span\>/", $html, $records);
preg_match_all("/\<span class\=\"values\"\>(.*?)\<\/span\>/", $html, $values);

$recordresult = $values[1];
$valueresult = $records[1];

$result  = array_combine($valueresult, $recordresult);
var_dump($result);