这个Perl正则表达式的PHP等价物是什么?

时间:2010-05-18 13:54:39

标签: php regex perl

这个Perl正则表达式的PHP等价物是什么?

if (/^([a-z0-9-]+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/
  and $1 ne "global" and $1 ne "") {
    print " <tr>\n";
    print "    <td>$1</td>\n";
    print "    <td>$2</td>\n";
    print "    <td>$3</td>\n";
    print "    <td>$4</td>\n";
    print "    <td>$5</td>\n";
    print "    <td>$6</td>\n";
    print "    <td>$7</td>\n";
    print "    <td>$8</td>\n";
    print " </tr>\n";
}

3 个答案:

答案 0 :(得分:7)

我建议你不要使用正则表达式,而是在空格上分割。您要检查的是由空格分隔的八列。

http://www.php.net/manual/en/function.preg-split.php处查看preg_split。它应该看起来像:

$fields = preg_split( '/\s+/', $string );
if ( $fields[0] == '...' ) 
...

答案 1 :(得分:6)

答案 2 :(得分:2)

PHP有一些functions that work with PCRE。所以试试这个:

if (preg_match('/^([a-z0-9-]+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/', $str, $match) && $match[1] != "global" && $match[1] != "") {
    print " <tr>\n";
    print "    <td>$match[1]</td>\n";
    print "    <td>$match[2]</td>\n";
    print "    <td>$match[3]</td>\n";
    print "    <td>$match[4]</td>\n";
    print "    <td>$match[5]</td>\n";
    print "    <td>$match[6]</td>\n";
    print "    <td>$match[7]</td>\n";
    print "    <td>$match[8]</td>\n";
    print " </tr>\n";
}