简体   繁体   中英

How to Extract the URL from A String in PHP?

I'm using PHP's "simplexml_load_file" to get some data from Flickr.

My goal is to get the photo url.

I'm able to get the following value (assigned to PHP variable):

<p><a href="http://www.flickr.com/people/19725893@N00/">codewrecker</a> posted a photo:</p>

<p><a href="http://www.flickr.com/photos/19725893@N00/2302759205/" title="Santa Monica Pier"><img src="http://farm3.static.flickr.com/2298/2302759205_4fb109f367_m.jpg" width="180" height="240" alt="Santa Monica Pier" /></a></p>

How can I extract just this part of it?

http://farm3.static.flickr.com/2298/2302759205_4fb109f367_m.jpg

Just in case it helps, here's the code I'm working with:

<?php
$xml = simplexml_load_file("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel");
foreach($xml->entry as $child) {
    $flickr_content = $child->content; // gets html including img url
    // how can I get the img url from "$flickr_content"???
 }
?>

You can probably get away with using a regular expression for this, assuming that the way the HTML is formed is pretty much going to stay the same, eg:

if (preg_match('/<img src="([^"]+)"/i', $string, $matches)) {
    $imageUrl = $matches[1];   
}

This is fairly un-robust, and if the HTML is going to change (eg the order of parameters in the <img> tag, risk of malformed HTML etc.), you would be better off using an HTML parser.

It's not solving your problem(and probably total overkill), but worth mentioning because I've used the library on 2 projects and it's well written.

phpFlickr - http://phpflickr.com/

Easy way: Combination of substr and strpos to extract first the tag and then the src='...' value, and finally the target string.

Slightly more difficult way (BUT MUCH MORE ROBUST): Use an XML parsing library such as simpleXML

I hope this is helpful. I enjoy using xpath to cut through the XML I get back from SimpleXML:

<?php
$xml = new SimpleXMLElement("http://api.flickr.com/services/feeds/photos_public.gne?id=19725893@N00&lang=en-us&format=xml&tags=carousel", NULL, True);
$images = $xml->xpath('//img');  //use xpath on the XML to find the img tags

foreach($images as $image){  
    echo $image['src'] ;  //here is the image URL
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM