简体   繁体   中英

PHP preg_replace regex, get number between parenthesis that might or might not contain _ and - sign

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM