dongling2038
2015-02-18 07:07 阅读 30
已采纳

如何在以下场景中仅从整个<img>标签获取图像URL?

I've an associative array titled $data as follows:

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" />
)
)

The actual array is very huge, here I've put in only the necessary data from array. Now what I want is for every element of the array the key [student_image] I should get only the URL of the image, no imag tag and any other data. In short I want following output of above array:

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
)
)

How should I achieve this in best possible and optimum way for all the elements of an array $data?

Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    duanrenchuo9244 duanrenchuo9244 2015-02-18 07:22

    try something like this:

       //$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);
    
    点赞 评论 复制链接分享
  • douzhan8303 douzhan8303 2015-02-18 07:18

    You can use a regular expression to extract the urls

    // $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);
    

    Hope this helps.

    点赞 评论 复制链接分享

相关推荐