Search code examples
phpregexpreg-match

Find only THIS part of the string PHP


I have a variable $string with the following layout inside :

image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"

How could I locate and set the url of thumb: to a new variable ie:

$thumb = 'http://static.web.com/scripts/image.php/44x44/442873.jpg';

BUT the thumb url (and all of the values) will be different every time the script is run (so I can't match the contents of the actual url).

Basically what function / functions do I need to use to :

1) search the entire string for thumb:

2) select everything in between the directly following quotation marks

3) store the result to a variable (without the "")


Solution

  • if this is part of a structured data format (json, xml) then you would be better off using a parser for said format.

    Failing that, given the information actually provided, a simple regex will do:

    $string = 'image: "http://web.com/files/images/442873_large.jpg",
    thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
    mp3: "http://web.com/files/clip/6240/23121376.mp3",
    waveform: "http://web.com/files/wave/23121376-wf.png"';
    
    preg_match("~thumb: \"(.*)\",~", $string, $matches);
    
    echo $matches[1];