PHP preg_replace 正则表达式,获取可能包含或不包含 _ 和 - 符号的括号之间的数字

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

这让我抓狂!我需要一个正则表达式来从字符串中提取数字。该数字可能包含 -(减号)或 _(下划线)符号,最好使用 preg_replace。

示例字符串:“这是 1 个带有(数字)(01230_12-3) 的示例(文本)”。

我需要提取的是(01230_12-3),但没有括号。

到目前为止,这是我拥有的:

$FolderTitle[$Counter]) = "This is 1 example (text) with a (number)(01230_12-3)";
$FolderNumber[$Counter] = preg_replace("/([^0-9-_])/imsxU", '', $FolderTitle[$Counter]);
  • 使用 preg_match() 时需要输出变量,因此我使用 shorthand 条件来确定是否存在匹配并将必要的值设置为 echo。
  • 您需要匹配前导 ( 然后 忘记 \K 然后匹配尽可能多的符合条件的字符。
  • None 个模式修饰符是必需的,所以我删除了它们。
  • 你可以用你的 $FolderNumber[$Counter] =
  • 替换我的 echo
  • 模式中的前导括号必须用 \ 转义。
  • \d 等同于 [0-9].

代码:(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';

输出:

01230_12-3