在字符串中查找单词,然后递增后面的整数


Find word in string, and increment the integer that comes after

这是为我的联系人系统准备的。

邮件的主题可以是:Hello Friend.RE^2 Hello Friend

我需要代码来确定主题是否有RE^{int} {subject},如果有,则使其为RE^{++int} {subject}

如果不是:则使其成为RE^2 {subject}

<?php
    preg_match('/^RE'^('d)*$/', $mail->subject , $m);
    if (empty ($m)) {
        $newSubject = 'RE^2 '.$mail->subject;
    } else {
        $reNum = $m[1]+1;
        // How to edit the subject to 'RE^{++num} {$mail->subject}' ?
    }
?>

您可以使用REGEX和preg_match来查找您的编号,如下所示:

$str = "RE^3 Hello Friend";
preg_match( '/RE'^('d*)/', $str , $m);
print_r( $m );
$number = $m[ 1 ]

最终结果可能是:

$subject = "Hello Friend";
preg_match( '/RE'^('d*)/', $subject , $m);
if ( empty ( $m )  ) 
    $newSubject = "RE^2 Hello Friend";
else{
    $number = $m[ 1 ] + 1;
    $newSubject = "RE^$number Hello Friend";
}
echo $newSubject;

要回答您的意见,这里是更改后的代码:

$subject = "Hello AbuRomaissae";
if ( !preg_match( '/RE'^('d*)/', $subject , $m)  ) 
    $newSubject = "RE^2 $subject";
else{
    $number = $m[ 1 ] + 1;
    $newSubject = "RE^$number ".preg_replace( '/RE'^('d*) /', "", $subject);
}
echo $newSubject;

此解决方案使用preg_replace_callback,因此您可以使用函数来处理替换。

$subject = 'Hello Friend';
$subject = 'RE^2 Hello Friend';
$subject = preg_replace_callback('/RE'^('d*)/', 'myFunc', $subject);
function myFunc($matches) {
  $x = ++$matches[0];
  return $x;
}
if (!preg_match('/RE'^'d*/', $subject)) { //if "RE^'d" is missing, add "RE^2"
  $subject = "RE^2 {$subject}";
}
echo $subject; //'RE^3 Hello Friend'