Reputation: 1753
I am new to regex and really don't have a clue. I have a MySql table looking like this:
id | grade | subject | kind | tally
1 | 11 | M | L | 1
2 | 11 | E | L | 3
3 | 11 | D | G | 1
4 | 11 | GK | G | 1
5 | 11 | SPA | G | 6
you get the idea...:)
Grade is an int, either 11,12 or 13. Subject is a string, between 1-4 "chars" long. Kind is either "L" or "G". Tally is an int, between 1 and 6.
This table is supposed to hold all of the classes/lessons there are at my school. When you write out the classname it would look something like this "11EL4" or "11ML1".
I want to be able to turn this "description" into grade, subject, kind and tally. For example:
function descriptionToArray($description){
// $grade = regex voodoo :)
// $subject = regex voodoo :)
// ...
return array("grade"=>$grade,"subject"=>$subject,...);
}
My guess would have been regex but I really don't know how that works (even after tutorials)
Upvotes: 1
Views: 821
Reputation: 23216
Try this:
if (preg_match('/(11|12|13)([A-Z]{1-4})(L|G)([1-6]{1})/', $class_string, $match)) {
list($dummy, $grade, $subject, $kind, $tally) = $match;
}
Explanation:
(11|12|13)
matches 11, 12 or 13([A-Z]+?)
matches 1 or more capital letters (ungreedy)(L|G)
matches an L
or a G
([1-6]{1})
matches a single digit in the range 1-6The $dummy
is required because $match[0]
will hold the entire regular expression match. Elements 1-4 will hold each patenthesised substring.
Upvotes: 3
Reputation: 1962
if you want to extract grade, subject or kind in different variables to do something on those then why not use a mysql_query to get those variables. If you want to make the classname from the data in the table, then get those variables from mysql_query and concatenate then to form your classname. and to make it an array put those variables in the array.
example:
//establish the mysql connection and select the database.
$query = mysql_query("SELECT * FROM class"); //Where class is your table name
while ($row = mysql_fetch_array($query)) { return array($row["grade"], $row["subject"], $row["kind"]); }
//Then use that array for whatever you want to use it for. Also assign a variable to it to use it outside the while loop.
Upvotes: 0
Reputation: 16055
Not much voodoo and kinda simple solution without regex could be:
function descriptionToArray($description){
$grade = substr($description, 0, 2);
$subject = substr($description, 2, strlen($description)-4);
$kind = substr($description, -2, -1);
$tally = substr($description, -1);
return array("grade" => $grade, "subject" => $subject, "kind" => $kind, "tally" => $tally);
}
Upvotes: 1