Regex & PHP - isolate src attribute from img tag

前端 未结 10 1396
眼角桃花
眼角桃花 2020-11-28 08:55

With PHP, how can I isolate the contents of the src attribute from $foo? The end result I\'m looking for would give me just \"http://example.com/img/image.jpg\"



        
相关标签:
10条回答
  • 2020-11-28 09:54

    Code

    <?php
        $foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />';
        $array = array();
        preg_match( '/src="([^"]*)"/i', $foo, $array ) ;
        print_r( $array[1] ) ;
    

    Output

    http://example.com/img/image.jpg
    
    0 讨论(0)
  • 2020-11-28 09:58

    lets assume i use

    $text ='<img src="blabla.jpg" alt="blabla" />';
    

    in

    getTextBetween('src="','"',$text);
    

    the codes will return :

    blabla.jpg" alt="blabla" 
    

    which is wrong, we want the codes to return the text between the attribute value quotes i.e attr = "value".

    so

      function getTextBetween($start, $end, $text)
                {
                    // explode the start string
                    $first_strip= end(explode($start,$text,2));
    
                    // explode the end string
                    $final_strip = explode($end,$first_strip)[0];
                    return $final_strip;
                }
    

    does the trick!.

    Try

       getTextBetween('src="','"',$text);
    

    will return:

    blabla.jpg
    

    Thanks all the same , because your solution gave me an insight to the final solution .

    0 讨论(0)
  • 2020-11-28 10:00

    try this pattern:

    '/< \s* img [^\>]* src \s* = \s* [\""\']? ( [^\""\'\s>]* )/'
    
    0 讨论(0)
  • 2020-11-28 10:02

    preg_match solves this problem nicely.

    See my answer here: How to extract img src, title and alt from html using php?

    0 讨论(0)
提交回复
热议问题