这让我疯了!我需要一个正则表达式从字符串中提取一个数字。该数字可能包括 - (减号)或_(下划线)符号,最好使用preg_replace。
示例字符串:“这是一个示例(文本),带有(数字)(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]);
答案 0 :(得分:1)
preg_match()
时,输出变量是必要的,所以我使用速记条件来确定是否存在匹配并为回声设置必要的值。(
然后忘记它与\K
匹配,然后匹配尽可能多的符合条件的字符。$FolderNumber[$Counter] =
\
进行转义。\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