-2

Okay this is probably all over the internet but I can't find a solution and been searching and trying different ways.

So the main way i've tried so far is as following:

string:

<div data-image-id="344231" style="height: 399.333px; background-image: url("/website/view_image/344231/medium"); background-size: contain;"></div>

code:

preg_match_all('/(style)=("[^"]*")/i', $value, $match);
preg_match('/background-image: url("(.*?)");/', $match[2][0], $match);
print_r($match);

I'm guessing I can't use:

background-image: url(" and "); instead the preg_match

Could someone give me some guidence on how I can achieve getting:

"/website/view_image/344231/medium"

YaBCK
  • 2,949
  • 4
  • 32
  • 61
  • 1
    I think you need to escape the first bracket after url `url\(` and the second closing brace `\)` – Dale Apr 06 '18 at 13:35
  • @Dale Please check updated question - How do i find it between the same strings with `"` added to the strings? – YaBCK Apr 06 '18 at 13:50
  • @mega6382 - If it's a minor issue please try and solve the question - thank you. – YaBCK Apr 06 '18 at 13:50
  • [H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ](https://stackoverflow.com/a/1732454/6998123) – mega6382 Apr 06 '18 at 13:52
  • 1
    @ChrisBeckett Try using the single quotes for background image url. And use this regex to capture it `background-image: url\('(.*?)'\);` – mega6382 Apr 06 '18 at 13:55

1 Answers1

2

If you use single quotes for the background image url instead of double quotes you could use DOMDocument and get the style attribute from the div.

Then use explode("; ") which will return an array where one item of that array will be "background-image: url('/website/view_image/344231/medium')".

Loop through the array and use preg_match with a regex like for example background-image: url\(([^)]+)\) which will capture in a group what is between the parenthesis.

If there is a regex match, store the value from the group.

$html = <<<HTML
<div data-image-id="344231" style="height: 399.333px; background-image: url('/website/view_image/344231/medium'); background-size: contain;"></div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($html);
$elm = $doc->getElementsByTagName("div");
$result = array ();
$style = $doc->getElementsByTagName("div")->item(0)->getAttribute("style");
foreach (explode("; ", $style) as $str)
    if (preg_match ('/background-image: url\(([^)]+)\)/', $str, $matches)) {
        $result[] = $matches[1];
    }
echo $result[0];

That will give you:

'/website/view_image/344231/medium'

Demo Php

The fourth bird
  • 154,723
  • 16
  • 55
  • 70