在数字字符类周围使用 wordboundaries的简单preg_match()
调用将完全准确并适合您的任务。
字边界元字符确保执行全整数匹配——不会发生误报(部分)匹配。
代码:(演示)
$array = array(
'text 1 2 and 3 text',
'text 3 9 25 text',
'text 9 25 48 text',
);
foreach ($array as $color) {
echo "\n---\n$color";
echo "\n\t" , preg_match('~\b[1-8]\b~', $color, $out) ? "checked (satisfied by {$out[0]})" : 'not found';
echo "\n\tChad says: " , (strpos($color,'1') || strpos($color,'2') || strpos($color,'3') || strpos($color,'4') || strpos($color,'5') || strpos($color,'6') || strpos($color,'7') || strpos($color,'8') ? 'found' : 'not found');
}
输出:
---
text 1 2 and 3 text
checked (satisfied by 1)
Chad says: found
---
text 3 9 25 text
checked (satisfied by 3)
Chad says: found
---
text 9 25 48 text
not found
Chad says: found
至于如何在你的脚本中实现这种技术......
if (!preg_match('~\b[1-8]\b~', $color)) {
echo 'checked';
}