2013-04-29 54 views
1

我试图输出一定数量的零取决于位数。我的代码不输出我想要的。PHP str_pad和strlen内preg_replace

$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) 
+2

您需要http://php.net/manual/en/function.preg-replace-callback.php为这 – 2013-04-29 18:26:27

回答

2

dev-null-dweller在评论中说,你应该使用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"; 
+1

感谢你们俩。这很好地工作。我不知道如何使用preg_replace_callback函数。以$ x作为示例使用 – user2001487 2013-04-29 18:42:45

1

我这样做哪些工作:

<?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); 

还有这个,如果你wan't最终输出的样子:0

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

。 strlen中的值需要是搜索字符串结果。 – user2001487 2013-04-29 18:39:10