simple html dom get in-line background-image URL from Attribute

3.9k views Asked by At

I'm trying to get CSS background-image URL from HTML Attribute using Simple HTML DOM . This the codes

$String=' <div class="Wrapper"><i style="background-image: url(https://example.com/backgroud-1035.jpg);" class="uiMediaThumbImg"></i></div>';
$html = new simple_html_dom();
$html->load($String); 
foreach($html->find('i') as $a0)
$src[$i++]=$a0->style;
foreach( $src as $css  ) 
print($css);

The output is Like this :-

background-image: url(https://example.com/backgroud-1035.jpg); 

All I want is strip background Url from the rest of CSS tags . Like this https://example.com/backgroud-1035.jpg

2

There are 2 answers

4
Burak On BEST ANSWER

You can use regex to strip out the text between parentheses.

foreach($html->find('i') as $a0){
    $style = $a0->style;
    preg_match('/\(([^)]+)\)/', $style, $match);
    $src[$i++] = $match[1];
    //echo $match[1];
}
2
Evara On

Maybe you found the answer, but for who did not I will use the explode() function so I can break the string into an array, see more about explode() function here. First I splited the $css variable into array. the array be like this:

background-image: url(https://example.com/backgroud-1035.jpg);" 
Array ( [0] => background-image: [1] => https://example.com/backgroud-1035.jpg);

And then break the ['1'] into array, then it looks like this

Array ( [0] => https://example.com/backgroud-1035.jpg [1] => ; )

And then print the ['0'] .

// it will output https://example.com/backgroud-1035.jpg 

full code:

    $String=' <div class="Wrapper"><i style="background-image: 
    url(https://example.com/backgroud-1035.jpg);" class="uiMediaThumbImg"></i></div>';
    $html = new simple_html_dom();
    $html->load($String); 
    foreach($html->find('i') as $a0)
    $src[$i++]=$a0->style;
    foreach( $src as $css  ) 
    
    $explode1 = explode("url(",$css);
    $explode2 = explode(")",$explode1['1']);
    print_r ($explode2['0']);