我有两个这样的字符串:
$a = "John, Male , Central Java";
$b = "name = John and gender= Male";
我希望这些字符串成为:
$a = "'John','Male','Central Java'";
$b = "username='John' and gender='Male'";
preg_replace 可以使用什么模式和替换来完成此任务?
我想创建一个这样的函数:
function select($what, $from, $filter) {
$query = "SELECT $what FROM $from WHERE $filter";
// Performing mysql query.
}
$result = select("*", "user", "username = John and gender = Male");
$查询输出:SELECT * FROM user WHERE username = John and gender = Male
但输出不是有效的 mysql 语法。所以我希望输出变成:
SELECT * FROM user WHERE username='John' and gender='Male'
我还想删除符号之间的空格。
解决方案:
我尝试了一些模式和替换,最后我找到了解决方案。我已经创建了格式化查询字符串的函数。我还使用&&
asAND
和||
as更改了字符串设置OR
。因此,即使值字符串包含'and'或'or',它也不会受到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);
输出:realname='Nanang El Agung' OR username='sarjono' AND password='123456'
此功能适用于$b
上述情况。