将字符串中的数字替换为短语编号


Replace numbers in string with phrase-number

在PHP中,我有一个值类似1 OR 21 AND (20 OR 3)的字符串。我想用后面跟着数字的短语来代替这些数字,使其成为condition1的意思:

1 OR 2=>condition1 OR condition2

1 AND (20 OR 3)=>condition1 AND (condition20 OR condition3)

我想我可以用preg_replace来做这件事,但我不知道怎么做。在替换过程中,我很难保持数字的值。

如果更容易的话,我也会接受javascript 中的答案

如果运算符的参数是字符串中唯一的数字,则可以执行:

$new = preg_replace( '/('d+)/', 'condition$1', $input);

这将匹配任何连续数字,并在捕获组中捕获它们,我们稍后在替换中将其称为$1

你可以从这个演示中看到,对于你的测试用例,这个输出:

condition1 OR condition2
condition1 AND (condition20 OR condition3)

您可以使用str_replace($search,$replace,$string)

$search can be array whatever you want to replace
$replace can alse be an array wherever you want to replace in a string
$string is a string where you want to change

这是你的问题的解决方案还是你想要其他东西?