regex preg_match for digit in middle for a string

前端 未结 3 590
走了就别回头了
走了就别回头了 2021-01-29 07:29
ddw_0_op1
ddw_1_op1
ddw_2_op1
ddw_3_op1
ddw_4_op1

in these strings of array how i can extract or preg_match only the number in middle that increase . t

相关标签:
3条回答
  • 2021-01-29 07:41

    I would break the string on underscore:

    $parts = explode('_', $string);
    $middle = $parts[1];
    
    0 讨论(0)
  • 2021-01-29 07:53

    If the number never exceeds a single digit, you could simply use $str[4] to get the fifth character of the string (your digit). On the other hand, however, if the numbers continue indefinitely, you could use either of the following regular expressions.

    Option 1

    See regex in use here

    (?<=_)\d+(?=_)
    
    • (?<=_) Positive lookbehind asserting what precedes is _
    • \d+ Matches one or more digits
    • (?=_) Positive lookahead asserting what follows is _

    Option 2

    See regex in use here: This method uses fewer steps than the previous.

    _\K\d+(?=_)
    
    • _ Match this literally
    • \K Resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
    • \d+ Matches one or more digits
    • (?=_) Positive lookahead asserting what follows is _
    0 讨论(0)
  • 2021-01-29 08:03

    use the preg_match function:

    $str = "ddw_01_fdfd";
    preg_match('/.+_([0-9]+)_.+/', $str, $matches);
    echo $matches[1];
    

    Output:

    01
    

    Another way to do it is by explode the string by _:

    $xpl = explode('_', $str);
    $middleStr = $xpl[1];
    

    The explode function splits a string by string, in that case create an array made by all substring contained in $str dividing them by _.

    Try it here.

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