假设我有字符串:"Test [[1294]] example"
我该怎么做才能preg_replace()
从双括号中提取数字?
获取该数字的(贪婪)表达式是什么?- 它始终是双括号内的整数。
假设我有字符串:"Test [[1294]] example"
我该怎么做才能preg_replace()
从双括号中提取数字?
获取该数字的(贪婪)表达式是什么?- 它始终是双括号内的整数。
你会使用preg_match()
,而不是preg_replace()
:
$subject = 'Test [[1294]] example';
preg_match('/\[\[(\d+)\]\]/', $subject, $match);
echo $match[1];
如果要“提取”数字,则无需preg_replace
. 使用preg_match
or preg_match_all
(如果有多次出现)代替:
preg_match('/\[\[(\d+)\]\]/', $input, $matches);
$integer = $matches[1];
或者
preg_match_all('/\[\[(\d+)\]\]/', $input, $matches);
$integerArray = $matches[1];
如果不是“提取”,您实际上的意思是“我如何preg_replace
使用这个术语并使用提取的整数”,您可以使用相同的正则表达式并引用捕获的整数,使用$1
:
$output = preg_replace('/\[\[(\d+)\]\]/', 'Found this integer -> $1 <-', $input);
这将导致:
Test Found this integer -> 1294 <- example