Reputation: 2220
I have some strings in PHP formed like this:
26301 - DEP : df 30 01 codename, CODE : cdef
the UPPERCASE parts are constants, while the other parts are variables.
so the pattern will be:
xxxxxx - DEP : yy zz kk wwwwwwww, CODE : ffff
the length of the variable parts could be different, so the constants will be only: DEP, the symbol ":", the symbol ",", CODE, and the symbol ":" again.
is there a way to extract those parts in PHP using a "pattern" or do I have to explode id with spaces, then check all the places to search for constants? any advice?
I would like to produce, from the first string:
$dep = "df 30";
$codenumber = "01";
$code = "cdef";
Upvotes: 1
Views: 116
Reputation: 14931
Using regex:
$str = '26301 - DEP : df 30 01 codename, CODE : cdef';
preg_match('/(.+) - DEP : (.+) (\d+) codename, CODE : (.+)/', $str, $array);
list($str, $line, $dep, $codenumber, $code) = $array;
echo "line: $line, dep: $dep, codenumber: $codenumber, code: $code";
// Result: line: 26301, dep: df 30, codenumber: 01, code: cdef
Upvotes: 1
Reputation: 11040
sscanf() is the way to go: http://www.php.net/manual/en/function.sscanf.php
In your case it could be something like this:
$var = "26301 - DEP : df 30 01 codename, CODE : cdef";
list($first, $second, $third, $fourth, $fifth, $sixth) = sscanf($var, "%d - DEP : %s %d %d %s, CODE : %s");
Upvotes: 1