正则表达式匹配数字字符串

时间:2012-07-15 10:28:57

标签: php regex 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函数。

3 个答案:

答案 0 :(得分: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';
}

答案 1 :(得分: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/>");
        }
    }
?>

编辑:通过一个简单的“黑客”,你现在可以使用“简单”的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/>";
        }
    }
?>

答案 2 :(得分: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()代替它们   会更快。