duanlushen8940 2013-09-11 02:15
浏览 36
已采纳

获取最后一次出现的String,作为数字,并替换它

I have strings like this

Foo(2)moreFoo (1)
Foo(1)moreFoo (2)
Foo(99)moreFoo (3)
Foo(99)moreFoo (9)
Foo

I need to take each string, and change the last (number)

So, in this case, I would like to get for each string:

Foo(2)moreFoo (2)
Foo(1)moreFoo (3)
Foo(99)moreFoo (4)
Foo(99)moreFoo (10)
Foo(1)

It would be like get the string, get the last occurence of (number), and replace it by (number +1)

How can I do this?

I've checked this answer, but not sure how to change it.

I've started with

$subject = 'Foo (2)(1)';

if(preg_match('\([0-9]+\)', $subject))
{   
    $pos = strrpos($subject, '\([0-9]+\)');

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }
}

but the problem is that could be that the number will be (10) so, I cannot just get the last 3 characters.

The (number), if exists, will be at end. It could be at middle, but the interesting one is in the end.

  • 写回答

2条回答 默认 最新

  • duanliang4009 2013-09-11 02:24
    关注

    You can use preg_replace_callback() to target the individual matches and replace them:

    echo preg_replace_callback('/\((\d+)\)$/m', function($match) {
        return '(' . ++$match[1] . ')';
    }, $subject);
    

    The pattern matches a parenthesized number at the end of each line and calls the anonymous function to perform the replacement. It uses $ combined with the /m modifier to match the end of each line.

    Matching lines that don't have any (number) you need a somewhat trickier expression:

    echo preg_replace_callback('/(?:\((\d+)\)|([^)]))$/m', function($match) {
        return isset($match[2]) ? "{$match[2]}(1)" : '(' . ++$match[1] . ')';
    }, $subject);
    

    The alternation matches either a (number) or something that's not a ) at the end of the line. If the line didn't end with ) we should add (1).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效