A simple and useful regular expression for beginners

A simple and useful regular expression for beginners

If this situation didn’t happen to you already, then I’m sure it will. Sometimes we have a database where one row contains a few rows from another table. In this situation, we have to check whether all the subordinate rows have a state of 1 (true).

From the database with the help comes the GROUP_CONCAT function.

I solved this with the example of MySQL query:

SELECT mt.*, (SELECT GROUP_CONCAT(st.state) FROM slave_table st WHERE = st.id_order) AS slaves_state FROM main_table mt WHERE mt.wys = '1' ORDER BY date DESC

variable slaves_state, for example, return might look like this:

1,1,1 (true)
1 (true)

Then we can determine color of row lines depending on whether any of its subordinate rows have a status of 1 (true), using regular expressions:

$is_all_slaves_true = preg_match('/^(1(,)?)+$/', $item->slaves_states, $matches);
 // mark true
 // mark false

Now I’ll explain this particular regular expression


^ – beginning of the sentence, $ – end of the sentence

Now we mark (…)  the first element which we want to check, and then in the middle we write 1, because only that value complies our conditions and (,)? , which  means that the comma may or may not occur, “+” at the end means that this situation has to happen at least once.

Regular expressions, at the beginning can make the problem for novice programmer, but for anyone who experienced them even just a little, the above equation should be simple 🙂