3

Possible Duplicate:
How can I convert ereg expressions to preg in PHP?

I'm working on a PHP script.

I have a URL of the form:

http://ecx.images-amazon.com/images/I/5104Xl51zFL._SL175_.jpg

and I simply want to grab the first part of the file name 5104Xl51zFL.

I'm pretty new to regexps but so far I have:

.*images\/I\/(.+?)(\.[^.]*|$)

which according to regextester.com should work but doesn't in my PHP.

Doesn't have to be a regexp if it's not the best solution.

If it's relevant here's my PHP (still debuggy):

function linkExtractor($html)
{
    if(preg_match_all('/<img ([^>]* )?src=[\"\']([^\"\']*\._SL175_\.jpe?g)[\"\']/Ui', $html, $matches, PREG_SET_ORDER)){
        foreach ($matches as $match) {
            $url = $match[2];
            echo "\n\n" .$url . "\nfile name: ";
            if(preg_match_all('.*images\/I\/(.+?)(\.[^.]*|$)', $url, $matched, PREG_SET_ORDER)) {
                foreach($matched as $name) {
                    print_r($matched);
                }
            }
        }
    }
}
Community
  • 1
  • 1
Max Bates
  • 1,238
  • 1
  • 16
  • 21

5 Answers5

8
$url = 'http://ecx.images-amazon.com/images/I/5104Xl51zFL._SL175_.jpg';
$path = parse_url($url, PHP_URL_PATH);
$filename = basename($path);
$partOne = strtok($filename, '.');
salathe
  • 51,324
  • 12
  • 104
  • 132
Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
1

This will match everything between /images/I/ and .

$url = 'http://ecx.images-amazon.com/images/I/5104Xl51zFL._SL175_.jpg';
if(preg_match('~/images/I/(.+?)\.~',$url,$match)) {
    $name = $match[1];
}
lafor
  • 12,472
  • 4
  • 32
  • 35
1

One way using regex:

$str='http://ecx.images-amazon.com/images/I/5104Xl51zFL._SL175_.jpg';
preg_match('/.*\/(.*?)\./',$str,$match);
print $match[1];

>>> 5104Xl51zFL

Explanation:

.*    # Match anything
\/    # Up to the last forwardslash (escaped)
(.*?) # Match anything after (captured, lazy)
\.    # Up to the first . (escaped)
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
1

If you're still looking for a regular expression to extract that part of the filename here is one:

([^/.]++)[^/]+$

This expression will match the full filename. Capture group 1 will contain every character in the filename that is before the first dot.

The ++ makes this regex faster than with only one +. This is because when a piece of text fails to match, the regex will fail more quickly.

Francis Gagnon
  • 3,545
  • 1
  • 16
  • 25
0
$file = basename("http://ecx.images-amazon.com/images/I/5104Xl51zFL._SL175_.jpg");
echo substr($file, 0, strpos($file, "."));

strpos is much faster than using regular expressions for something that simple

Koval
  • 145
  • 8