How can I find, increment and replace in php?

前端 未结 3 1107
死守一世寂寞
死守一世寂寞 2021-01-23 01:03

I have strings in the form \\d+_\\d+ and I want to add 1 to the second number. Since my explanation is so very clear, let me give you a few examples:

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-23 01:33

    Use explode (step-by-step):

    $string = "123456_2";
    
    echo $string;
    
    $parts = explode("_", $string);
    
    $lastpart = (int)$parts[1];
    
    $lastpart++;
    
    $newstring = $parts[0] . "_" . (string)$lastpart;
    
    echo $newstring;
    

    This separates the string on the "_" character and converts the second part to an integer. After incrementing the integer, the string is recreated.

提交回复
热议问题