-3

我不太擅长正则表达式。有人可以帮我吗?

$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函数。

4

3 回答 3

2

这是数组的解决方案:

// 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';
}
于 2012-07-15T11:13:56.413 回答
0

简单的:

<?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/>";
        }
    }
?>
于 2012-07-15T10:40:57.820 回答
0
$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() ,因为它们会更快。

于 2012-07-15T10:47:43.653 回答