4

如何在php中修剪一些单词?像这样的例子

pid="5" OR pid="3" OR

我想删除最后一个OR

4

5 回答 5

12

我建议使用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 的答案是您问题的真正答案,这些只是需要考虑的一些替代方案。

于 2010-06-19T07:11:11.487 回答
7

您可以尝试rtrim

rtrim — 从字符串末尾去除空格(或其他字符)

$string = "pid='5' OR pid='3' OR";
echo rtrim($string, "OR"); //outputs pid='5' OR pid='3'
于 2010-06-19T07:02:16.207 回答
4

使用substr查找并删除结尾OR

$string = "pid='5' OR pid='3' OR";
if(substr($string, -3) == ' OR') {
  $string = substr($string, 0, -3);
}
echo $string;
于 2010-06-19T07:41:17.813 回答
2

正则表达式也可以:

$str = 'pid="5" OR pid="3" OR';
print preg_replace('/\sOR$/', '', $str);
于 2010-06-19T07:39:18.397 回答
1

你怎么看待这件事?

$str='pid="5" OR pid="3" OR';    
$new_str=substr($str,0, strlen($str)-3);
于 2010-06-19T08:47:58.963 回答