对此帖进行跟进: How to extract img src, title and alt from html using php?
我想格式化数组,我有这个例子:
$articletxt = 'Hello! this is my picture <format type="table" name="My Picture" data="http://www.domain.com/myimage.jpg" caption="I look tired" /> But I look better in real life <br><br> Hello! this is my picture <format type="youtube" name="Unlock Samsung S5310 Galaxy Pocket Neo by USB" data="piHMEZlAAmA" /> But I look better in real life';
preg_match_all('/<format[^>]+>/i',$articletxt, $formatbusquedas);
$img = array();
foreach( $formatbusquedas[0] as $img_tag) {
preg_match_all('/(type|name|data)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}
echo '<pre>';
print_r($img);
它将打印出来:
Array
(
[<format tipo="table" name="My Picture" data="http://www.domain.com/myimage.jpg" caption="I look tired" />] => Array
(
[0] => Array
(
[0] => tipo="table"
[1] => name="My Picture"
[2] => data="http://www.domain.com/myimage.jpg"
)
[1] => Array
(
[0] => tipo
[1] => name
[2] => data
)
[2] => Array
(
[0] => "table"
[1] => "My Picture"
[2] => "http://www.domain.com/myimage.jpg"
)
)
[<format tipo="youtube" name="Unlock Samsung S5310 Galaxy Pocket Neo by USB" data="piHMEZlAAmA" />] => Array
(
[0] => Array
(
[0] => tipo="youtube"
[1] => name="Unlock Samsung S5310 Galaxy Pocket Neo by USB"
[2] => data="piHMEZlAAmA"
)
[1] => Array
(
[0] => tipo
[1] => name
[2] => data
)
[2] => Array
(
[0] => "youtube"
[1] => "Unlock Samsung S5310 Galaxy Pocket Neo by USB"
[2] => "piHMEZlAAmA"
)
)
)
但我需要这样:
Array
(
[<format tipo="table" name="My Picture" data="http://www.domain.com/myimage.jpg" caption="I look tired" />] => Array
(
[tipo] => table
[name] => My Picture
[data] => http://www.domain.com/myimage.jpg
)
[<format tipo="youtube" name="Unlock Samsung S5310 Galaxy Pocket Neo by USB" data="piHMEZlAAmA" />] => Array
(
[tipo] => youtube
[name] => Unlock Samsung S5310 Galaxy Pocket Neo by USB
[data] => piHMEZlAAmA
)
)
如何做到这一点?
答案 0 :(得分:0)
您可以通过将array_combine
应用于其每个元素来修改$img
数组,以生成所需的输出。
foreach ($img as &$value) { // be sure to use a reference here.
$value = array_combine($value[1], $value[2]);
}