简体   繁体   English

如何在PHP中替换/删除字符串中的单词

[英]How to replace/remove word in a string in php

I've a string like this: 我有一个像这样的字符串:

SELECT * FROM `backplanechanneldecoder20141002`  AND  WHERE  Z0 = '1'

I want to remove AND from it. 我想从中删除AND。 I tried using 我尝试使用

$sql_total = str_replace("AND WHERE", "WHERE", $sql_total);
$sql_total = str_replace("AND  WHERE", "WHERE", $sql_total);

but it didn't work. 但这没用。

Looks like there's more than one space in between "AND" and "WHERE". 看起来在“ AND”和“ WHERE”之间有多个空格。 You could deal with this using a regular expression: 您可以使用正则表达式处理此问题:

$sql_total = preg_replace('/AND\s+WHERE/', 'WHERE', $sql_total);

The \\s+ part of the expression matches one or more space characters. 表达式的\\s+部分与一个或多个空格字符匹配。

As mentioned in the comments, it's unclear how you have ended up with this string in the first place. 如评论中所述,目前尚不清楚您最初如何使用此字符串。 It looks as though you're trying to generate a query string programmatically but haven't dealt correctly with the first/only "WHERE" clause. 似乎您正在尝试以编程方式生成查询字符串,但未正确处理第一个/唯一的“ WHERE”子句。 It would clearly be better to address the cause of this issue, rather than fixing the symptom. 解决此问题的原因显然比解决症状要好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM