php regular expression to convert string followed by number into multiple strings each followed by one of the digits

前端 未结 2 1736
南旧
南旧 2021-01-27 03:02

how to i replace

Apple 123456

to

Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6

by php pcre?

相关标签:
2条回答
  • 2021-01-27 03:35

    With this one you get partially what you want:

    <?php
        echo preg_replace('/([0-9])/', 'Apple $1|', 'Apple 123456');
    

    That results in: Apple Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6|

    For removing the first "Apple" you could str_replace() or explode() the initial string, resulting something like

    <?php
        $string = 'Apple 123456';
        $string = str_replace("Apple", "", $string);
        echo preg_replace('/([0-9])/', 'Apple $1|', $string);
    

    The result here is Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6|. You can remove the last pipe by using substr($result, 0, -1).

    The final code will look like this:

    <?php
        $string = 'Apple 123456';
        $string = str_replace("Apple", "", $string);
        $regex = preg_replace('/([0-9])/', 'Apple $1|', $string);
        echo substr($regex, 0, -1);
    
    0 讨论(0)
  • 2021-01-27 03:42

    Modified version of Bogdan's regex using negative lookahead.

    Replace number with "number|Apple " unless it is the last character in the string.

    <?
    $string = "Apple 123456";
    echo preg_replace('/([0-9])(?!$)/', '$1|Apple ', $string);
    ?>
    

    Ouput: Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6

    0 讨论(0)
提交回复
热议问题