我有一个$play
由字符和数字组成的变量。例如:
$play = "blah05"
我怎么用preg_match()
只能得到05?我的$regexp
正确吗?
$regexp = "/^[^0-9]/";
if (preg_match($regexp, $play, $matches)) {
echo "matches[0]";
}
我有一个$play
由字符和数字组成的变量。例如:
$play = "blah05"
我怎么用preg_match()
只能得到05?我的$regexp
正确吗?
$regexp = "/^[^0-9]/";
if (preg_match($regexp, $play, $matches)) {
echo "matches[0]";
}
如果你想从最后得到数字,正则表达式应该是这样的:
$regexp = '/(\d+)$/';
如果您想从字符串中的任何位置获取数字:
$regexp = '/(\d+)/';
只需var_dump($matches);
查看结果并选择最适合您的选项即可。
if (preg_match($regexp, $play, $matches)) {
var_dump($matches);
}
尝试:
$regexp = "/([0-9]+)$/";
if (preg_match($regexp, $play, $matches)) {
echo $matches[1];
}
这将捕获在字符串末尾具有数字的那些,如果您想捕获在字符串中任何位置具有数字的那些,请删除 $。
$regexp = "/[0-9]+/";
if (preg_match($regexp, $play, $matches)) {
echo $matches[0];
}
[0-9] 是数字。并且使用 + 你匹配至少一个数字(尽可能多)。