Search code examples
phpregexpreg-match

PHP Preg match - get wrapped value


I d like to extract all wrapped text value using preg match

So

background: url("images/gone.png");
color: #333;
...

background: url("images/good.png");
font-weight: bold;

From above string, I want to grab

images/gone.png
images/good.png

What will be the right command line for this?


Solution

  • In php, you should this:

    $str = <<<CSS
        background: url("images/gone.png");
        color: #333;
    
        background: url("images/good.png");
        font-weight: bold;
    CSS;
    
    preg_match_all('/url\("(.*?)"\)/', $str, $matches);
    var_dump($matches);
    

    Then, you will see something like this as an output:

    array(2) {
      [0]=>
      array(2) {
        [0]=>
        string(22) "url("images/gone.png")"
        [1]=>
        string(22) "url("images/good.png")"
      }
      [1]=>
      array(2) {
        [0]=>
        string(15) "images/gone.png"
        [1]=>
        string(15) "images/good.png"
      }
    }
    

    Therefore, the list with the urls will be in $matches[1] :)