Search code examples
phpregexdatabasedenormalized

PHP Regex pattern needed for MySQL database manupilation


I have some columns in my table, descriptions column contains some information like;

a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20

with a SQL command, i need to update it.

In there, I'll use a PHP function for updating, if first and second parameters exist in current records (in description column) together.

Eg: if user wants to change the value of description that includes a1b01,Value 1 I'll execute a SQL command like that;

function do_action ($code,$value,$new1,$new2,$newresult) {
UPDATE the_table SET descriptions = REPLACE(descriptions, $code.','.$value.'*', $code.','.$value.','.$new1.','.$new2.','.$newresult)";
}
  • (star) indicates that, these part is unknown (This is why i need a regex)

My question is : how can i get

a1b01,Value 1,2,1,60| 

part from below string

a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20 

via regex, but a1b01 and Value 1 should be get as parameter.

I just want that; when I call do_action like that;

do_action ("a1b01","Value 1",2,3,25);

record will be : a1b01,Value 1,2,3,25|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20
(first part is updated...)


Solution

  • You don't necessarily need to use a regular expression to do this, you could use the explode function since it is all delimited

    So you could do as follows:

    $descriptionArray = explode('|', $descriptions); //creates array of the a1b01,Value 1,2,1,60 block
    //then for each description explode on ,
    for($i = 0; i < count($descriptionArray); $i++){
        $parameters = explode(',', $descriptionArray[$i]); 
        do_action ($parameters[0],$parameters[1],$parameters[2],$parameters[3],$parameters[4]);
    }