Artykuły na każdy temat
[PHP] Pobieranie rozszerzenia pliku z podanej ścieżki
<?php
function first_method($path)
{
return substr($path, (strrpos($path, '.' ) + 1));
}
function second_method($path)
{
return substr(strrchr($path, '.'), 1);
}
function third_method($path)
{
return end(explode('.', $path));
}
function fourth_method($path)
{
return pathinfo($path, PATHINFO_EXTENSION);
}
function fifth_method($path)
{
return basename($path);
}
function sixth_method($path)
{
// Imperfectly, but works sometimes
preg_match('#^(?:.+?)(?:\.([^\.]*))?$#', $path, $matches);
return $matches[1];
}
$some_address[0] = 'http://www.example.com/path/test.ext';
$some_address[1] = 'http://www.example.com/path/test.ext.ext2';
$some_address[2] = 'http://www.example.com/path/.htaccess';
$some_address[3] = 'http://www.example.com/path/test';
$some_address[4] = 'http://www.example.com/path/test.';
$some_address[5] = './test.ext';
$some_address[6] = '/test.ext';
$some_address[7] = 'test.ext.ext2';
// Oczywiście jest więcej kombinacji dlatego proponuje przetestować je osobiście
echo '<pre>';
for($h = 0, $how = count($some_address); $h < $how; ++$h)
{
echo '<div style="color: red">first_method(\''.$some_address[$h].'\') - '.first_method($some_address[$h]).'</div>';
echo '<div style="color: orange">second_method(\''.$some_address[$h].'\') - '.second_method($some_address[$h]).'</div>';
echo '<div style="color: green">third_method(\''.$some_address[$h].'\') - '.third_method($some_address[$h]).'</div>';
echo '<div style="color: blue">fourth_method(\''.$some_address[$h].'\') - '.fourth_method($some_address[$h]).'</div>';
echo '<div style="color: navy">fifth_method(\''.$some_address[$h].'\') - '.fifth_method($some_address[$h]).'</div>';
echo '<div style="color: purple; border-bottom: 1px solid black">sixth_method(\''.$some_address[$h].'\') - '.sixth_method($some_address[$h]).'</div>';
}
echo '</pre>';
?>
Użyte w kodzie wyrażenie regularne nie jest perfekcyjne dlatego proponuje poprawić je
Komentarze
Dodaj komentarz