通过PHP过滤

时间:2009-12-21 01:52:44

标签: php filter

我在第1列的$ data显示了我:

“AAA123” “ABC1234” “ABD123” “BAC12” “CAB123” “DA125” 等等..

我想显示仅以“AB”开头的$ data,它在第1列显示为:

“ABC1234” “ABD123”

不是其他人,而是与“ABC1234”和“ABD123”相关的其他行和列


提前完成。

Sample structure http://img706.imageshack.us/img706/8994/34310422.jpg

3 个答案:

答案 0 :(得分:3)

如果$data是一个字符串数组,则可以使用array_filter

PHP 5.3或更高版本:

$AB = array_filter($data, function($str) {
    return 'AB' == substr($str, 0, 2);
});
PHP 5.3之前的

$AB = array_filter($data, 
                   create_function('$str', 
                                   'return "AB" == substr($str, 0, 2);'
                  )               );

或者:

function create_prefix_tester($prefix) {
    return create_function('$str', 
                  "return '$prefix' == substr(\$str, 0, " . strlen($prefix) . ');'
                  );
}
$AB = array_filter($data, create_prefix_tester('AB'));

或者您可以使用循环:

foreach ($data as $str) {
    if ('AB' ==  substr($str, 0, 2)) {
      // do stuff
      ...
    }
}

修改

从示例代码中,您似乎想要循环:

while (FALSE !== ($line = fgets($fp))) {
    $row = explode('|', $line); // split() is deprecated
    if ('AB' == substr($row[0], 0, 2)) {
        switch($sortby) {
        case 'schools': // fallthru
        default:
            $sortValue = $row[0];
            break;
        case 'dates':
            $sortValue = $row[1];
            break;
        case 'times':
            $sortValue = $row[2];
            break;
        }
        array_unshift($row, $sortValue);
        $table[] = $row;
    }
}

或:

function cmp_schools($a, $b) {
    return strcmp($a[0], $b[0]);
}
function cmp_dates($a, $b) {
    return $a['datestamp'] - $b['datestamp'];
}
function cmp_times($a, $b) {
    return $a['timestamp'] - $b['timestamp'];
}
while (FALSE !== ($line = fgets($fp))) {
    $row = explode('|', $line); // split() is deprecated
    if ('AB' == substr($row[0], 0, 2)) {
        $when = strtotime($row[1] + ' ' + $row[2]);
        $row['timestamp'] = $when % (60*60*24);
        $row['datestamp'] = $when - $row['timestamp'];
        $table[] = $row;
    }
}
usort($table, 'cmp_' + $sortby);

答案 1 :(得分:2)

我只想使用substr(),如下面的代码段所示:

if (substr($str, 0, 2) == 'AB') {
  // The string is right.
}

答案 2 :(得分:1)

使用strposhttp://www.php.net/manual/en/function.strpos.php),例如

if (strpos($my_string, "AB") === 0) {
  <do stuff>
}

请务必使用===代替==,因为如果未找到“AB”,则该函数将返回false,使用==等于0。