This is driving me nuts! I need a regex to extract a number from a string. The number might include a - (minus) or _ (underscore) sign, preferably using preg_replace.
The example string: "This is 1 example (text) with a (number)(01230_12-3)".
What I need to extract is the (01230_12-3), but without the parenthesis.
So far, this is what I have:
$FolderTitle[$Counter]) = "This is 1 example (text) with a (number)(01230_12-3)";
$FolderNumber[$Counter] = preg_replace("/([^0-9-_])/imsxU", '', $FolderTitle[$Counter]);
- When using
preg_match()
an output variable is necessary, so I am using a shorthand conditional to determine if there was a match and setting the necessary value to the echo.
- You need to match the leading
(
then forget it with \K
then match as many of the qualifying characters as possible.
- None of those pattern modifiers were necessary, so I removed them.
- You can replace my echo with your
$FolderNumber[$Counter] =
- the leading parenthesis in the pattern must be escaped with
\
.
\d
is the same as [0-9]
.
Code: (Demo)
$Counter = 0;
$FolderTitle[$Counter] = "This is 1 example (text) with a (number)(01230_12-3)";
echo preg_match("/\(\K[-\d_]+/", $FolderTitle[$Counter], $out) ? $out[0] : 'no match';
Output:
01230_12-3