我想从我的字符串变量中提取出4个唯一的数字......这意味着,如果它有12345
我不希望它给我1234
...我想要抓住一组只有4个数字的数字。
我当前的字符串有:
echo $code
打印
your code is 34 4325 23453 342
我真的只想打印
4325
非常感谢我能得到的任何帮助!
答案 0 :(得分:1)
尝试以下代码
preg_match_all('/(\d{4})/', $text, $matches);
return $matches;
答案 1 :(得分:0)
您只需将preg_match_all
与regex
\b(\d{4})\b
上述正则表达式检查长度为4
所以你的代码看起来像
preg_match_all("/\b(\d{4})\b/",$str,$m);
print_r($m);
答案 2 :(得分:0)
<?php
$input = 'your code is 34 4325 23453 342';
// 1. extract all numbers
preg_match_all('/\d+/', $input, $m);
// 2. find all 4-digits numbers with 4 distinct digits
foreach ($m[0] as $number) {
if (strlen($number) == 4) {
if ($number[0] != $number[1] && $number[0] != $number[2] && $number[0] != $number[3] && $number[1] != $number[2] && $number[1] != $number[3] && $number[2] != $number[3]) {
echo $number, PHP_EOL;
}
}
}
答案 3 :(得分:0)
$code = 'your code is 34 4325 23453 342';
echo preg_replace('/.*?(\d{4}).*/', '$1', $code); //outputs 4325
答案 4 :(得分:0)
好吧,如果你想要每个4位数字块的唯一数字,你会得到这样的正则表达式:
\b(\d)(?!\1)(\d)(?!\1|\2)(\d)(?!\1|\2|\3)(\d)\b
我认为你应该使用这样的反向引用,我找不到另一种方法来做它..
检查每个数字(\ d)是否与之前的数字不同