Vidya_tr Posted April 1, 2009 Share Posted April 1, 2009 Suppose my file is 'sample.flv'. Using the code below, preg_match('/^(.*)(\..*)?$/', $name, $matches); $extension = $matches[2]; I expect to get $extension=.flv .But I get nothing in $extension. please help me to fix the error. Link to comment https://forums.phpfreaks.com/topic/152035-solved-problem-with-preg_match/ Share on other sites More sharing options...
thebadbad Posted April 1, 2009 Share Posted April 1, 2009 You need to make the first parenthesized pattern non-greedy, so it won't just match the whole string, and leave nothing for the rest of the pattern. Do it by adding a question mark after the asterisk: <?php $name = 'sample.flv'; preg_match('/^(.*?)(\..*)?$/', $name, $matches); $extension = $matches[2]; ?> But that code will only work on filenames without dots in the name. A simple and faster way to get the file extension every time: <?php $name = 'sample.new.flv'; $parts = explode('.', $name); $extension = end($parts); ?> Link to comment https://forums.phpfreaks.com/topic/152035-solved-problem-with-preg_match/#findComment-798430 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.