regex preg_match for digit in middle for a string

孤人 提交于 2020-01-30 13:05:44

问题


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 . thanks in advance


回答1:


I would break the string on underscore:

$parts = explode('_', $string);
$middle = $parts[1];



回答2:


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 _



回答3:


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.



来源:https://stackoverflow.com/questions/48627563/regex-preg-match-for-digit-in-middle-for-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!