如何在php中修剪一些单词?像这样的例子
pid="5" OR pid="3" OR
我想删除最后一个OR
我建议使用implode()
这样的 SQL 表达式。首先构建一个简单表达式的数组,然后用 OR 将它们内爆:
$pids = array('pid = "5"', 'pid = "3"');
$sql_where = implode(' OR ', $pids);
现在$sql_where
是字符串'pid = "5" OR pid = "3"'
。您不必担心剩余的 OR,即使$pids
.
此外,一个完全不同的解决方案是附加" false"
到您的 SQL 字符串,这样它就会结束,"... OR false"
这将使它成为一个有效的表达式。
@RussellDias 的答案是您问题的真正答案,这些只是需要考虑的一些替代方案。
您可以尝试rtrim:
rtrim — 从字符串末尾去除空格(或其他字符)
$string = "pid='5' OR pid='3' OR";
echo rtrim($string, "OR"); //outputs pid='5' OR pid='3'
使用substr查找并删除结尾OR
:
$string = "pid='5' OR pid='3' OR";
if(substr($string, -3) == ' OR') {
$string = substr($string, 0, -3);
}
echo $string;
正则表达式也可以:
$str = 'pid="5" OR pid="3" OR';
print preg_replace('/\sOR$/', '', $str);
你怎么看待这件事?
$str='pid="5" OR pid="3" OR';
$new_str=substr($str,0, strlen($str)-3);