如何仅从<;img>;标记


How to get the image URL only from the whole <img> tag in following scenario?

我有一个名为$data的关联数组,如下所示:

Array
(
    [0] => Array
        (
[student_image] => <img src="http://34.144.40.142/file/pic/photo/2015/02/02ff1a23db112db834b8f41748242bcb_240.png"  alt=""  width="180"  height="160"  class="photo_holder" />
)
    [1] => Array
        (
[student_image] => <img src="http://34.144.40.142/theme/frontend/foxplus/style/default/image/document/docx.png"  alt="" />
)
[2] => Array
        (
 [student_image] => <img src="http://34.144.40.142/file/pic/photo/2015/02/da46580276da5c3a31b75e8b31d35ddf_240.png"  alt=""  width="180"  height="160"  class="photo_holder" />
)
)

实际的数组非常巨大,这里我只输入了数组中必需的数据。现在我想要的是,对于数组的每个元素,关键字[student_image],我应该只得到图像的URL,而不是imag标记和任何其他数据。简而言之,我想要上面数组的以下输出:

Array
(
    [0] => Array
        (
[student_image] => http://34.144.40.142/file/pic/photo/2015/02/02ff1a23db112db834b8f41748242bcb_240.png
)
    [1] => Array
        (
[student_image] => http://34.144.40.142/theme/frontend/foxplus/style/default/image/document/docx.png"
)
[2] => Array
        (
 [student_image] => http://34.144.40.142/file/pic/photo/2015/02/da46580276da5c3a31b75e8b31d35ddf_240.png
)
)

对于数组$data的所有元素,我应该如何以最佳方式实现这一点?

提前谢谢。

试试这样的东西:

   //$data is your array
    $data = array_map(function($elem){
       //$elem is each elemet  of you array
       return array('student_image' => preg_replace('/<img'ssrc="([^"]+)".+$/','$1',$elem['student_image']));
    },$data);

您可以使用正则表达式提取URL

// $data is your existing array with img tags
$urls = array();
foreach ($data as $key => $value){
    foreach ($value as $key1 => $img) {
        preg_match('/<img[^>]*src="([^"]*)"[^>]*'/>/', $img, $srcmatch);
        $urls[$key][$key1] = $srcmatch[1];
    }
}
// now $urls is having only image url and have same structure of $data,
// You may replace $urls with $data
var_dump($urls);

希望这能有所帮助。