我不太擅长正则表达式。有人可以帮我吗?
$string = '1,2,3,4,7,8,10,11,14,17,18,19,22,23,26,29,30';
preg_match('/(\d*,*)(2,)(\d*,*)(4,)(\d*,*)(8)/', $string);
一直以来,这个字符串必须是字符串,不能是数组或其他任何东西。假设我正在寻找数字 2、4、8(但不是 18)。我正在使用 PHP 和preg_match
函数。
我不太擅长正则表达式。有人可以帮我吗?
$string = '1,2,3,4,7,8,10,11,14,17,18,19,22,23,26,29,30';
preg_match('/(\d*,*)(2,)(\d*,*)(4,)(\d*,*)(8)/', $string);
一直以来,这个字符串必须是字符串,不能是数组或其他任何东西。假设我正在寻找数字 2、4、8(但不是 18)。我正在使用 PHP 和preg_match
函数。
这是数组的解决方案:
// explode a string to array of numbers
$haystack = explode(',', $string);
// define numbers to search
$needle = array(2,4,48);
// define found elements
$found = array_intersect($needle, $haystack);
// print found elements
if ($found) {
print 'Found: ' . implode(',', $found);
}
和 preg_match 的解决方案:
// add "," to the beginning and string end
$string = ",$string,";
// define pattern to search (search for 14, 19 or 20)
$pattern = '/,14|19|20,/';
// if pattern is found then display Hello
if (preg_match($pattern, $string)) {
print 'Hello';
}
简单的:
<?php
$string = '1,2,3,4,7,8,10,11,14,17,18,19,22,23,26,29,30';
$search = array(2, 4, 8);
$parts = explode(",", $string);
array_flip($parts);
foreach($search as $n){
if(isset($parts[$n])){
echo ("found ".$n."<br/>");
}
}
?>
编辑:通过简单的“hack”,您现在可以使用“easy” preg_match():
<?php
$string = '1,2,3,4,7,8,10,11,14,17,18,19,22,23,26,29,30';
$string = ','.$string.',';
$search = array("2", "4", "8");
foreach($search as $n){
if(preg_match("#,$n,#", $string)){
echo "found $n <br/>";
}
}
?>
$string = '1,2,3,4,7,8,10,11,14,17,18,19,22,23,26,29,30';
$search = array('2', '4', '8'); # or $search = explode(',', '2,4,8');
foreach($search as $number)
if (strpos($string, $number) === false)
echo $number, ' not found!';
如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用 preg_match()。请改用 strpos() 或 strstr() ,因为它们会更快。