使用 preg_replace 时如何增加替换字符串中的计数?

发布于 2024-08-19 15:40:26 字数 178 浏览 4 评论 0原文

我有这样的代码:

$count = 0;    
preg_replace('/test/', 'test'. $count, $content,-1,$count);

对于每次替换,我都会获得 test0.

我想要 test0、test1、test2 等。

I have this code :

$count = 0;    
preg_replace('/test/', 'test'. $count, $content,-1,$count);

For every replace, I obtain test0.

I would like to get test0, test1, test2 etc..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

真心难拥有 2024-08-26 15:40:26

使用 preg_replace_callback()

$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);

function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}

Use preg_replace_callback():

$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);

function rep_count($matches) {
  global $count;
  return 'test' . $count++;
}
暗恋未遂 2024-08-26 15:40:26

使用 preg_replace_callback()

class TestReplace {
    protected $_count = 0;

    public function replace($pattern, $text) {
        $this->_count = 0;
        return preg_replace_callback($pattern, array($this, '_callback'), $text);
    }

    public function _callback($matches) {
        return 'test' . $this->_count++;
    }
}

$replacer = new TestReplace();
$replacer->replace('/test/', 'test test test'); // 'test0 test1 test2'

注意:使用 global 是硬而快速的解决方案,但它会带来一些问题,所以我不推荐它。

Use preg_replace_callback():

class TestReplace {
    protected $_count = 0;

    public function replace($pattern, $text) {
        $this->_count = 0;
        return preg_replace_callback($pattern, array($this, '_callback'), $text);
    }

    public function _callback($matches) {
        return 'test' . $this->_count++;
    }
}

$replacer = new TestReplace();
$replacer->replace('/test/', 'test test test'); // 'test0 test1 test2'

Note: Using global is the hard-and-fast solution but it introduces some problems, so I don't recommend it.

堇色安年 2024-08-26 15:40:26

PHP5.3 发布后,我们现在可以使用闭包和 use 关键字来解决上面 Emil 提出的 global 问题:

    $text = "item1,\nitem2,\nFINDME:23623,\nfoo1,\nfoo2,\nfoo3,\nFINDME:923653245,\nbar1,\nbar2,\nFINDME:43572342,\nbar3,\nbar4";
$pattern = '/FINDME:(\d+)/';
$count = 1;
$text = preg_replace_callback(  $pattern
                            ,   function($match) use (&$count) {
                                    $str = "Found match $count: {$match[1]}!";
                                    $count++;
                                    return $str;
                                }
                            ,   $text
                            );
echo "<pre>$text</pre>";

返回:

item1,
item2,
Found match 1: 23623!,
foo1,
foo2,
foo3,
Found match 2: 923653245!,
bar1,
bar2,
Found match 3: 43572342!,
bar3,
bar4

注意 在函数名称后面使用 (&$count) - 这允许我们在函数范围内读取 $count ( & 使其通过引用传递,因此可以从函数的范围)。

Following the release of PHP5.3 we can now use a closure and the use keyword to get around the global issue raised by Emil above:

    $text = "item1,\nitem2,\nFINDME:23623,\nfoo1,\nfoo2,\nfoo3,\nFINDME:923653245,\nbar1,\nbar2,\nFINDME:43572342,\nbar3,\nbar4";
$pattern = '/FINDME:(\d+)/';
$count = 1;
$text = preg_replace_callback(  $pattern
                            ,   function($match) use (&$count) {
                                    $str = "Found match $count: {$match[1]}!";
                                    $count++;
                                    return $str;
                                }
                            ,   $text
                            );
echo "<pre>$text</pre>";

Which returns:

item1,
item2,
Found match 1: 23623!,
foo1,
foo2,
foo3,
Found match 2: 923653245!,
bar1,
bar2,
Found match 3: 43572342!,
bar3,
bar4

Note the use (&$count) following the function name - this allows us to read $count in the scope of the function (the & making it passed by reference and therefore writeable from the scope of the function).

酒废 2024-08-26 15:40:26

另外,如果您想避免使用全局:

$count = 0;
preg_replace_callback('/test/', 函数rep_count($matches) use (&$count) {
返回 '​​测试' 。 $计数++;
}, $内容);

Also, if you want to avoid using global:

$count = 0;
preg_replace_callback('/test/', function rep_count($matches) use (&$count) {
return 'test' . $count++;
}, $content);

断念 2024-08-26 15:40:26

您只需在回调函数中定义一个静态变量:

$result = preg_replace_callback('/test/', function ($m) {
    static $count = 0;
    return 'test' . $count++;
}, $content);

这样就不会污染全局命名空间。


对于这种特定情况,您还可以使用简单的函数:

$parts = explode('test', $content);
$end = array_pop($parts);
$result = '';

foreach($parts as $k=>$v) {
    $result .= 'test' . $k;
}

$result .= $end;

You only have to define a static variable in the callback function:

$result = preg_replace_callback('/test/', function ($m) {
    static $count = 0;
    return 'test' . $count++;
}, $content);

This way you don't pollute the global namespace.


For this specific case you can also use simple functions:

$parts = explode('test', $content);
$end = array_pop($parts);
$result = '';

foreach($parts as $k=>$v) {
    $result .= 'test' . $k;
}

$result .= $end;
一花一树开 2024-08-26 15:40:26

preg_replace_callback()将允许您在退回火柴进行后续更换之前对火柴进行操作。

preg_replace_callback() will allow you to operate upon the match before returning it for subsequent replacement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文