1

有一个包含数字数据的字符串变量,比如说$x = "OP/99/DIR";。数字数据的位置可以在任何情况下根据用户的需要在应用程序中修改,斜线可以被任何其他字符改变;但数字数据是强制性的。如何将数字数据替换为不同的数字?示例OP/99/DIR更改为OP/100/DIR.

4

4 回答 4

2

假设这个数字只出现一次:

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

仅更改第一次出现:

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

于 2012-07-12T10:44:38.630 回答
2

使用正则表达式和 preg_replace

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

print $x;
于 2012-07-12T10:46:46.300 回答
2
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);

print $string;

输出:

OP/100/DIR 
于 2012-07-12T10:46:58.197 回答
1

最灵活的解决方案是使用 preg_replace_callback() 这样你就可以对匹配做任何你想做的事情。这匹配字符串中的单个数字,然后将其替换为数字加一。

root@xxx:~# 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);
?>
root@xxx:~# 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
)
于 2012-07-12T10:50:16.450 回答