如何使preg_replace具有替换次数的计数功能?

时间:2011-01-27 14:30:37

标签: php

我已经创建了一个preg_replace脚本但现在我想在其中添加count函数!

我的代码

$replace = 'ISO Burning Programs/Active@ ISO Burner 2.1.0.0/SPTDinst-v162-x86.exe';
$result=preg_replace('/[^0-9^A-Z^a-z-*… ,;_!@.{}#<>""=-^:()\[\]]/', '<br/>', $replace);
echo $result;

输出

ISO Burning Programs
Active@ ISO Burner 2.1.0.0
SPTDinst-v162-x86.exe

但我想要的输出是 -

1 ISO Burning Programs
2 Active@ ISO Burner 2.1.0.0
3 SPTDinst-v162-x86.exe

任何人都可以帮助我吗? 在此先感谢!!!!!!

3 个答案:

答案 0 :(得分:1)

或者你可以这样做:

$replace = 'ISO Burning Programs/Active@ ISO Burner 2.1.0.0/SPTDinst-v162-x86.exe';
$result = explode('/', $replace);

foreach($result as $i => $value)
    printf("%d %s<br />", ++$i, $value);

答案 1 :(得分:1)

如果您想使用preg执行此操作,则必须使用preg_replace_callback

$result = preg_replace_callback('/([^\/]*)(\/|$)/', function($matches){
    static $count = 0;
    $count++;
    return !empty($matches[1]) ? $count.' '.$matches[1].'<br/>' : '';
}, $replace);

答案 2 :(得分:0)

    preg_replace has a count function in it, the -1 is limit (unlimited) and $count is the number of replacement. just FYI.

    $result=preg_replace('/[^0-9^A-Z^a-z-*… ,;_!@.{}#<>""=-^:()\[\]]/', '<br/>\n', $replace, -1, $count);

    $a = explode("\n", $result);
    $i=1;
foreach($a as $res)
    {
    echo $i . " " . $res;
$i++;
    }
相关问题