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]);
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. (
then forget it with \\K
then match as many of the qualifying characters as possible. $FolderNumber[$Counter] =
\\
. \\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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.