2012-07-12 179 views
1

有一个包含数字数据的字符串变量,如$x = "OP/99/DIR";。数字数据的位置可以在任何情况下通过用户需求在应用程序内部修改而改变,并且斜杠可以被任何其他字符改变;但号码数据是强制性的。如何将数字数据替换为不同的数字?示例OP/99/DIR更改为OP/100/DIR如何将字符串中的数字数据替换为不同的数字?

回答

2
$string="OP/99/DIR"; 
$replace_number=100; 
$string = preg_replace('!\d+!', $replace_number, $string); 

print $string; 

输出:

OP/100/DIR 
2

假设的数目只发生一次:

$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);

只改变第一次出现:

$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);

2

使用正则表达式和的preg_replace

$x="OP/99/DIR"; 
$new = 100; 
$x=preg_replace('/\d+/e','$new',$x); 

print $x; 
+0

它和alexey的回答非常相似,所以使用'!'有什么区别? – pheromix 2012-07-12 10:54:01

+0

我使用了e修饰符,以便您可以在第二个参数中执行任何操作。关于!,实际上没有什么区别。它只是一个分隔符。检查http://www.php.net/manual/en/regexp.reference.delimiters.php。 – Jithin 2012-07-12 11:00:09

1

最灵活的解决方案是使用preg_replace_callback(),所以你可以做任何你想要的比赛。这匹配字符串中的单个数字,然后将其替换为数字加1。

[email protected]:~# more test.php 
<?php 
function callback($matches) { 
    //If there's another match, do something, if invalid 
    return $matches[0] + 1; 
} 

$d[] = "OP/9/DIR"; 
$d[] = "9\$OP\$DIR"; 
$d[] = "DIR%OP%9"; 
$d[] = "OP/9321/DIR"; 
$d[] = "9321\$OP\$DIR"; 
$d[] = "DIR%OP%9321"; 

//Change regexp to use the proper separator if needed 
$d2 = preg_replace_callback("(\d+)","callback",$d); 

print_r($d2); 
?> 
[email protected]:~# php test.php 
Array 
(
    [0] => OP/10/DIR 
    [1] => 10$OP$DIR 
    [2] => DIR%OP%10 
    [3] => OP/9322/DIR 
    [4] => 9322$OP$DIR 
    [5] => DIR%OP%9322 
)