【问题标题】:PHP str_pad and strlen within preg_replacepreg_replace 中的 PHP str_pad 和 strlen
【发布时间】:2013-04-29 18:22:56
【问题描述】:

我正在尝试根据位数输出一定数量的零。我的代码没有输出我想要的。

$x = '12345';
$y = preg_replace('/(\d+)/', str_pad('',(12-strlen("$1")),0), $x);
echo "y = $y";

# expected output: y = 0000000 (7 zeros)
# output: y = 0000000000 (10 zeros)

【问题讨论】:

标签: php preg-replace strlen


【解决方案1】:

就像dev-null-dweller在cmets中说的你应该使用preg_replace_callback()

// This requires PHP 5.3+
$x = '12345';
$y = preg_replace_callback('/\d+/', function($m){
    return(str_pad('', 12 - strlen($m[0]), 0));
}, $x);
echo "y = $y";

【讨论】:

  • 谢谢你们俩。这很好用。我不知道如何使用 preg_replace_callback 函数。
【解决方案2】:

我做了这个,效果很好:

<?php
$x = '12345';
$y = str_pad(preg_replace('/(\d+)/', "0", $x), 12 - strlen($x), "0", STR_PAD_LEFT);
echo "y = $y";

也有这个正则表达式版本:

$y = str_pad(preg_replace('/\d/', "0", $x), 12 - strlen($x), "0", STR_PAD_LEFT);

还有这个,如果你不希望最终输出看起来像:0012345

$y = str_pad($x, 7, "0", STR_PAD_LEFT);

【讨论】:

  • $x 用作示例。 strlen 中的值需要是搜索字符串结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多