在字符串中查找数字并向其中添加50

flu*_*lux 0 php

我想找到一个字符串中的所有数字并添加50.

所以我从头开始:

'text' => string 'Word (9), WordSomething (5)'
'text' => string 'Word (15)'
Run Code Online (Sandbox Code Playgroud)

结果:

'text' => string 'Word (59), WordSomething (55)'
'text' => string 'Word (65)'
Run Code Online (Sandbox Code Playgroud)

nic*_*ckb 9

您可以使用正则表达式来捕获括号中的数字,然后使用preg_replace_callback()以下方法应用您自己的自定义回调:

$result = preg_replace_callback( '/\((\d+)\)/', function( $match) {
    return '(' . ($match[1] + 50) . ')';
}, $string);
Run Code Online (Sandbox Code Playgroud)

所以,给定这个输入字符串:

Word (9), WordSomething (5)
Run Code Online (Sandbox Code Playgroud)

输出将是:

Word (59), WordSomething (55)
Run Code Online (Sandbox Code Playgroud)

对于变量输入,请使用闭包:

$number = 50;
$result = preg_replace_callback( '/\((\d+)\)/', function( $match) use( $number) {
    return '(' . ($match[1] + $number) . ')';
}, $string);
Run Code Online (Sandbox Code Playgroud)