php regexp question
How to catch and filer the below开发者_JS百科 filename
Input:
../images/imgac00000001.jpg
../images/imgbc00000002.jpg
../images/img1111.jpg
Outout:
imgac00000001
imgbc00000002
I have tried in PHP using preg_replace, which I dont howto use correctly.
preg_replace('/(img)[a-z]{0,2}[0-9]*/i', '$1', $img_path);
Thanks
An easy way to fetch file names :
$file_info = pathinfo('../images/imgac00000001.jpg');
print $file_info['filename'];
You need to use preg_match_all
, not preg_replace
$input = <<<EOF
../images/imgac00000001.jpg
../images/imgbc00000002.jpg
../images/img1111.jpg
EOF;
//imgac00000001
//imgbc00000002
preg_match_all('/img[a-z]{0,2}[0-9]*/i', $input, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => imgac00000001
[1] => imgbc00000002
[2] => img1111
)
)
If the base path is the same, why not use str_replace?
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
$image = "../images/imgac00000001.jpg";
$name = str_replace(array('../images/','.jpg','.png'),'',$image);
You could use str_ireplace()
for a case insensitive situation.
Manual on str_replace
Try preg_replace('/((img)[a-z]{0,2}[0-9]*)/i', '$1', $img_path);
put extra parenthesis around the whole expression.
You don't need a regex, you could do something this:
$str = '../images/imgac00000001.jpg';
$str = array_shift(explode('.', end(explode('/', $str))));
But here's your regex:
$str = '../images/imgac00000001.jpg';
preg_match('/\/([^\/\.]+)\./', $str, $matches);
精彩评论