2016-02-24 94 views
0

給予跟進它這個帖子: 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

您可以修改$img陣列,方法是將array_combine應用於每個元素以生成所需的輸出。

foreach ($img as &$value) { // be sure to use a reference here. 
    $value = array_combine($value[1], $value[2]); 
}