PHP find url in sa text and save in array -
i have txt file , want save in array urls starting http:// , ends .png or .jpg or .jpeg. how can that?
can use this?
<?php function geturls($string) { $regex = '/https?\:\/\/[^\" ]+/i'; preg_match_all($regex, $string, $matches); return ($matches[0]); } $urls = geturls($string); foreach($urls $url) { echo $url.'<br />'; } ?>
is correct?
the function showed not work because there's nothing specifying .png
, .jpg
, or .jpeg
in regex. return first match: $matches[0]
. additionally, needs /g
flag find multiple instances in same string (/i
ignores case).
try instead:
<?php function geturls($string) { // \w word character $regex = '/https?\:\/\/[\w]+\.(jpg|png|jpeg)/ig'; preg_match_all($regex, $string, $matches); return ($matches); } $urls = geturls($string); foreach($urls $url) { echo $url.'<br />'; } ?>
Comments
Post a Comment