tags:

views:

102

answers:

3

What would be the PHP equivalent of this Perl regex?

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";
}
+6  A: 

preg_match

hsz
Excellent. thanks very much!However, in preg_match how do I do it like perl where you have $1, $2, $3 etc.?Hope that makes sense!
Jamie
Read the docs he linked to: "If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on."
Scott Saunders
+2  A: 

PHP has some functions that work with PCRE. So try this:

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";
}
Gumbo
Excellent! thank you! :-)
Jamie
You might want to check `$match[1]` is set before testing other conditions, to avoid notices / warnings on lines that don't match the expected input.
Greg K
Gumbo
Ah yes, thanks. I knew this but failed to spot it here.
Greg K
+7  A: 

I'd suggest that rather than using a regex, you split on whitespace. All you're checking for is eight columns separated by whitespace.

Look at preg_split at http://www.php.net/manual/en/function.preg-split.php. It should look something like:

$fields = preg_split( '/\s+/', $string );
if ( $fields[0] == '...' ) 
...
Andy Lester
Good idea! Thank you :-)
Jamie