如何在PHP中处理字符串?
问题描述:
我有这种情况:如何在PHP中处理字符串?
print_r($test);
echo '<br>';
$and = '';
for ($i=0; $i<$count; $i++){
$and.= ' u.room = '.$test[$i];
$and.= ' OR ';
}
的结果将是:
Array ([0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6)
u.room = 1 OR u.room = 3 OR u.room = 4 OR u.room = 5 OR u.room = 6 OR
我想是删除最后一个“或”这样的字符串将成为:u.room = 1 OR u.room = 3 OR u.room = 4 OR u.room = 5 OR u.room = 6
任何想法?
感谢
答
for ($i=0; $i<$count; $i++){
$and.= ' u.room = '.$test[$i];
if ($i != $count-1) {
$and.= ' OR ';
}
}
答
使用另一个阵列效果很好,用implode产生最终的字符串:
$clauses = array();
foreach($test as $t) {
$clauses[] = "u.root = {t[$i]}";
}
$ands = implode(',', $clauses);
然而,对于你的情况下,如果它是一个场和多个值,你可以去在其他地方:
$in = implode(',', $test);
$sql = " ... WHERE u.room IN ($in)";
+0
确保在'$ test'所有值都正确转义,以避免SQL注入攻击,虽然。例如,如果你使用的是MySQL,可以这样做:'$ test = array_map('mysql_real_escape_string',$ test);' – elazar
答
更简单(尽管不完全相同,如果$test
为空):
$and = "u.room = " . implode(" OR u.room = ", $test);
成功,得益于 – Patrioticcow