Php 如何将字符串中的数字数据替换为其他数字?

Php 如何将字符串中的数字数据替换为其他数字?,php,Php,有一个字符串变量包含数字数据,例如$x=“OP/99/DIR”。数字数据的位置可以根据用户的意愿在任何情况下通过在应用程序内部修改而改变,斜杠可以通过任何其他字符改变;但数字数据是强制性的。如何将数字数据替换为其他数字?示例OP/99/DIR更改为OP/100/DIR假设数字只出现一次: $content=str\u replace($originalText,$numberToReplace,$numberToReplaceWith) 要仅更改第一次发生,请执行以下操作: $content=s

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

假设数字只出现一次:

$content=str\u replace($originalText,$numberToReplace,$numberToReplaceWith)

要仅更改第一次发生,请执行以下操作:


$content=str\u replace($originalText,$numberToReplace,$numberToReplaceWith,1)

假设数字只出现一次:

$content=str\u replace($originalText,$numberToReplace,$numberToReplaceWith)

要仅更改第一次发生,请执行以下操作:


$content=str\u replace($originalText,$numberToReplace,$numberToReplaceWith,1)

使用正则表达式和preg\u替换

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

print $x;

使用regex和preg_替换

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

print $x;
输出:

OP/100/DIR 
输出:

OP/100/DIR 

最灵活的解决方案是使用preg_replace_callback(),这样就可以对匹配项执行任何操作。这将匹配字符串中的单个数字,然后将其替换为数字加1

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
)
root@xxx:~#more test.php

最灵活的解决方案是使用preg_replace_callback(),这样就可以对匹配项执行任何操作。这将匹配字符串中的单个数字,然后将其替换为数字加1

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
)
root@xxx:~#more test.php

这与alexey的答案完全相同,那么使用
有什么区别呢?我使用了e修饰符,以便您可以执行第二个参数中的任何内容。关于!,其实没有什么区别。它只是一个分隔符。检查。这和阿列克西的答案完全一样,那么使用
有什么区别呢?我使用了e修饰符,以便您可以执行第二个参数中的任何内容。关于!,其实没有什么区别。它只是一个分隔符。检查。