我有以下字符串,我必须传递给mysql_query()函数。当有人尝试搜索我网站中的某些数据时,这种刺痛是动态生成的。现在的问题是每个单词后面没有结束引号。
and purpose="Buy and property_type="Home and property_nature="Residential and city =" Lahore"
我希望这个字符串采用以下形式:
and purpose="Buy" and property_type="Home" and property_nature="Residential" and city =" Lahore"
谢谢
不知道为什么要这样做,而不仅仅是在创建字符串时修复字符串,您可能正在寻找一个正则表达式,例如使用负面回溯的正则表达式/(?<!") and/
:
$string = 'and purpose="Buy and property_type="Home" and property_nature="Residential and city =" Lahore"';
$string = preg_replace('/(?<!") and/', $string);
var_dump($string);
这给了
和目的="购买"和property_type="家"和property_nature="住宅"和城市="拉合尔"
代码板演示。
正则表达式 101 演示
这也会自动"Home" and
更改为"Home"" and
,因为它确保还没有报价。
使用 PDO 和预准备语句。也许是这样的:
$stmt = $db->prepare('SELECT ... WHERE ... AND purpose = :purpose AND property_type = :property_type AND property_nature = :property_nature AND city = :city');
$stmt->bindParam(':purpose', $_POST[...]);
$stmt->bindParam(':property_type', $_POST[...]);
$stmt->bindParam(':property_nature', $_POST[...]);
$stmt->bindParam(':city', $_POST[...]);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
如果要
使用旧的API,则解决方案是mysql_real_escape_string。不过,我建议查看更新的方法和变量绑定。