note 126767 deleted from function.strrchr by cmb
| From: | cmb@php.net | Date: | Sun, 16 Jan 2022 13:50:03 +0000 |
| Subject: | note 126767 deleted from function.strrchr by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217499@lists.php.net to get a copy of this message | ||
Note Submitter: msegit post pl
----
After @jphansen, to extract portion of string (i.e. path), note that strrchr() returns false if
needle is not found.
You should use rather:
<?php
$path = '/www/public.htm/index.html';
$filename = substr(strrchr($path, "/"), 1) ?: (strrchr($path,
"/")==="/" ? "" : $path); /* code#1 */
// but NOT: $filename = substr(strrchr($path, "/"), 1); see below because
echo $filename; // "index.html"
// because:
$path = '/www/public.htm/index.html'; echo substr(strrchr($path, "/"), 1); //
"index.html" - OK.
$path = 'index.html'; echo substr(strrchr($path, "/"), 1); // "" -
WRONG, should be "index.html"
$path = '/www/public.htm/'; echo substr(strrchr($path, "/"), 1); // ""
- OK.
// Compare with basename() :
echo basename($path); // "public.htm"
// but
echo substr(strrchr($path, "/"), 1) ?: (strrchr($path, "/")==="/" ?
"" : $path); /* code#1 */ // ""
// BTW, to extract file extension with strrchr():
$extension = substr(strrchr(strrchr($path, '/') ?: $path, "."), 1);
// example, with note about pathinfo(), basename()
function ext($path) {
$ext = substr(strrchr(strrchr($path, '/') ?: $path, "."), 1);
// for demonstration:
$info = pathinfo($path);
echo str_pad($path, 30, ' '), ' ; ', str_pad($ext, 10, ' '),
' ; ', str_pad($info['extension'], 10, ' '),
' ; ', str_pad(substr(strrchr($path, "/"), 1) ?: (strrchr($path,
"/")==="/" ? "" : $path), 10, ' '), ' ; ',
basename($path), PHP_EOL;
return $ext;
}
// demonstration
echo 'String: ; ext(): ; p&ie: ; filename as code#1: ;
basename(): ', PHP_EOL, '( p&ie = pathinfo() and $info[\'extension\']
)', PHP_EOL;
ext('/www/public.htm/index.html');
ext('index.html');
ext('/www/public.htm/');
ext('/www/public.htm/index');
ext('index.');
?>
demonstration result:
String: ; ext(): ; p&ie: ; filename as code#1: ; basename():
( p&ie = pathinfo() and $info['extension'] )
/www/public.htm/index.html ; html ; html ; index.html ; index.html
index.html ; html ; html ; index.html ; index.html
/www/public.htm/ ; ; htm ; ; public.htm
/www/public.htm/index ; ; ; index ; index
index. ; ; ; index. ; index.