I have two string like this:
$a = "John, Male , Central Java";
$b = "name = John and gender= Male";
I want these string to become:
$a = "'John','Male','Central Java'";
$b = "username='John' and gender='Male'";
What pattern and replacement would work with preg_replace to accomplish this?
I want to create a function like this:
function select($what, $from, $filter) {
$query = "SELECT $what FROM $from WHERE $filter";
// Performing mysql query.
}
$result = select("*", "user", "username = John and gender = Male");
$quer Output: SELECT * FROM user WHERE username = John and gender = Male
But the output is not valid mysql syntax. So I want the output to become:
SELECT * FROM user WHERE username='John' and gender='Male'
I also want to remove the space between symbols.
Solution:
I have try some pattern and replacement and finaly I found the solution. I've create function to format the query string. I also change the string setting with using &&
as AND
and ||
as OR
. So, even when the value string contains 'and' or 'or', it's would not affected by preg_replace.
// Preg replace sample: -> string = string space && string = space
function format_query($qry_string) {
// Remove spaces before and after '='.
$qry_string = preg_replace("/(\s+\=)/", "=", $qry_string);
// string= string space && string= space
$qry_string = preg_replace("/(\=\s+)/", "=", $qry_string);
// string=string space && string=space
// Add single quote between '=' and word than contain space after the word.
$qry_string = preg_replace("/\=(\w+\s+)/", "='$1", $qry_string);
// string='string space && string=space
// Add single quote in first and end of words that start after '=' and not contain space after the word.
$qry_string = preg_replace("/\=(\w+)/", "='$1'", $qry_string);
// string='string space && string='space'
// Add single quote in end of words before of keyword '&&' and '||'.
$qry_string = preg_replace("/(\w+)\s+\&\&/", "$1' &&", $qry_string);
// string='string space' && string='space'
$qry_string = preg_replace("/(\w+)\s+\|\|/", "$1' ||", $qry_string);
// Replate keyword '&&' and '||' to 'and' and 'or'
$qry_string = str_replace("&&", "AND", $qry_string);
$qry_string = str_replace("||", "OR", $qry_string);
return $qry_string;
}
$string = "realname = Nanang El Agung || username = sarjono && password = 123456";
echo format_query($string);
OUTPUT: realname='Nanang El Agung' OR username='sarjono' AND password='123456'
This function is works fine for $b
above.