1.use regular expression to get filename from a file full path name.
function get_filename($data){
$preg = '///([^//]*)$/si';
preg_match_all($preg, $data, $match);
$nlast = count($match[1])-1;
if($nlast>=0)
{
$ret = trim($match[1][$nlast]);
return $ret;
}
else return "";
}
$preg = '///([^//]*)$/si';
//The meaning is find the character string which will be start with "/" but no "/" in the string.
function get_filepath($data){
$preg = '/(.*)///si';
preg_match_all($preg, $data, $match);
$nlast = count($match[1])-1;
if($nlast>=0)
{
$ret = trim($match[1][$nlast]);
return $ret;
}
else return "";
}
(.*)贪婪获取
function get_filename($data){
$preg = '///([^//]*)$/si';
preg_match_all($preg, $data, $match);
$nlast = count($match[1])-1;
if($nlast>=0)
{
$ret = trim($match[1][$nlast]);
return $ret;
}
else return "";
}
$preg = '///([^//]*)$/si';
//The meaning is find the character string which will be start with "/" but no "/" in the string.
function get_filepath($data){
$preg = '/(.*)///si';
preg_match_all($preg, $data, $match);
$nlast = count($match[1])-1;
if($nlast>=0)
{
$ret = trim($match[1][$nlast]);
return $ret;
}
else return "";
}
(.*)贪婪获取
贪婪与懒惰
当正则表达式中包含能接受重复的限定符时,通常的行为是(在使整个表达式能得到匹配的前提下)匹配尽可能多的字符。考虑这个表达式:a.*b,它将会匹配最长的以a开始,以b结束的字符串。如果用它来搜索aabab的话,它会匹配整个字符串aabab。这被称为贪婪匹配。
有时,我们更需要懒惰匹配,也就是匹配尽可能少的字符。前面给出的限定符都可以被转化为懒惰匹配模式,只要在它后面加上一个问号?。这样.*?就意味着匹配任意数量的重复,但是在能使整个匹配成功的前提下使用最少的重复。现在看看懒惰版的例子吧:
a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab(第一到第三个字符)和ab(第四到第五个字符)。
为什么第一个匹配是aab(第一到第三个字符)而不是ab(第二到第三个字符)?简单地说,因为正则表达式有另一条规则,比懒惰/贪婪规则的优先级更高:最先开始的匹配拥有最高的优先权——The match that begins earliest wins。