如何删除后面的所有数字并只保留最后一个
问题描述:
我想删除除最后一个之外的所有数字。如何删除后面的所有数字并只保留最后一个
例子:
test test 1 1 1 255 255 test 7.log
我想变换:
test test test 255 7.log
我试过无数的组合,但我发现这个结果最好的是错误的:
test test 55 test 7.log
我感谢大家为我们提供的宝贵帮助e很棒。
答
,如果你需要删除所有数字,除了最后:
$file = "test test 1 1 1 255 255 test 7.log";
list($name, $ext) = explode('.', $file);
// split the file into chunks
$chunks = explode(' ', $name);
$new_chunks = array();
// find all numeric positions
foreach($chunks as $k => $v) {
if(is_numeric($v))
$new_chunks[] = $k;
}
// remove the last position
array_pop($new_chunks);
// for any numeric position delete if from our list
foreach($new_chunks as $k => $v) {
unset($chunks[$v]);
}
// merge the chunks again.
$file = implode(' ', $chunks) . '.' .$ext;
var_dump($file);
输出:
string(20) "test test test 7.log"
如果你想,然后删除所有dublicate号码:
$file = "test test 1 1 1 255 255 test 7.log";
list($name, $ext) = explode('.', $file);
$chunks = explode(' ', $name);
$new_chunks = array();
$output = array();
foreach($chunks as $k => $v) {
if(is_numeric($v)){
if(!in_array($v, $new_chunks)) {
$output[] = $v;
$new_chunks[] = $v;
}} else
$output[] = $v;
}
var_dump(implode(' ', $output). '.' .$ext);
输出:
string(26) "test test 1 255 test 7.log"
做一些谷歌之前询问 – 2013-02-22 13:07:50
请发布到底你试过什么代码。如果我们只看到您的尝试结果,我们无法帮助您。 – Cerbrus 2013-02-22 13:12:05
如果你说你为什么试图做到这一点,甚至可能会有更好的方法。 – Ollie 2013-02-22 13:16:47