我在PHP中遇到preg_replace函数的问题。我想不出一个模式和一个替代品。
我有这两个字符串和一些代码:
$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';
$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);
$dirname1 = end($pieces1); // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php
$output = preg_replace($pattern, $replacement, $dirname1); // or (..,..,$dirname2
echo $output; // i need 1min(without period_) or abcdrfg (without .php)
UPD:
function Cat($dirname)
{
$name = explode('/', $dirname);
$pattern = ???;
$replacement = ???;
return preg_replace($pattern, $replacement, $dirname1);
}
print(Cat('hdadas/dasdad/dasd/period_1min'))); // output need 1min only
print(Cat('hdadas/dasdad/dasd/period_1min/abcdrfg.php'))); // output need abcdrfg only
这个正则表达式如何/^.+_|\.[^.]+$/
:
$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';
$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);
$dirname1 = end($pieces1); // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php
$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname1); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)
$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname2); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)
输出:
1min
abcdrfg
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句