I’ve strings like constant-string-NUMBER-*
where
constant-string-
is a costant string (that I know and can use in the effort of getting the NUMBER) e.g.fix-str-
NUMBER
is any natural number-*
can be any string
String-result examples:
fix-str-0
// result: 0
fix-str-0-another-str
// result: 0
fix-str-123
// result: 123
fix-str-456789
// result: 456789
fix-str-123456789-yet-another-str
// result: 1234567899
fix-str-999999-another-str-123
// result: 999999
I would like to extract the NUMBER from those strings in PHP so that I can associate this number to a variable e.g. $numberFromString = ?
.
Any insight?
3
Answers
You can represent a string as an array of characters. Use the PHP substr() Function, where the second argument is the number from which your string is left.
Example. Return "world" from the string:
Info from here: https://www.w3schools.com/php/func_string_substr.asp
Try this:
fix-str-
match this string.(d+)
followed by one or more digits, and save the number inside the first capturing group.EDIT
From @user3783243, we can also use
fix-str-Kd+
, without the need of a capturing group.fix-str-
match this string, then..K
reset the starting point of the reported match.d+
then match one or more digits.See regex demo
Based on your string examples, there are two possible ways. One way could use
explode
, then of course the other way could be withpreg_match
for regex. I’ll show both ways, only to show that regex is not always absolutely necessary.Using
explode
:Using
preg_match
: