php - Get number between two characters
Get the solution ↓↓↓Solution:
preg_match('/_(\d+)_/', $str, $matches);
$number = (int) $matches[1];
Answer
Solution:
Because your sample strings appear consistently formatted, you do not need to include the validation of matching the trailing underscore.
Withpreg_match()
, match the literal underscore, then forget that you matched it (using\K
), then match one or more digits. The match will be a string -- if you need an integer type, then cast the string to anint
.
If you definitely want the number to be cast as an integer, PHP offers a more direct function:sscanf()
. Silently consume the one or more non-underscore characters, then the underscore, then capture the one or more digit number and use%d
to dictate that the value must be anint
type variable.
Codes: (Demo)
preg_match('/_\K\d+/', $test, $match);
var_export($match[0]);
Or
sscanf($test, '%*[^_]_%d', $integer);
var_export($integer);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: npm err! code 1
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.