我有一些包含LIMIT 3, 199
或LIMIT 0, 100
字样的字符串。
基本上我想在我的字符串中替换LIMIT一词及其后的所有内容。
我如何在PHP中执行此操作? str_replace只替换一个项目和LIMIT文本后面是动态/
所以它可能是
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121
// RETURN WOULD BE
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT
WHEN JOHN TRIED LIMIT 343, 333 HE FOUND
// RETURN WOULD BE
WHEN JOHN TRIED
答案 0 :(得分:3)
使用strpos
查找字符串中LIMIT
的位置,然后使用substr
将字符串返回到该点。真的很基本的字符串操作。
如果你想要一个单行,也许可以使用preg_replace
,但我不认为这里需要使用正则表达式工具集。
答案 1 :(得分:2)
使用模式LIMIT.+$
preg_replace
替换/LIMIT.+$/m
也就是说:
$string = preg_replace("/LIMIT.+$/m","",$string);
答案 2 :(得分:0)
答案 3 :(得分:0)
正如我建议您在不理解它们时使用正则表达式时,这里是一个不使用它们的简单答案(请注意,我建议学习正则表达式,但它们不容易学习):
$output = substr($input, 0, strpos($input, 'LIMIT'))
答案 4 :(得分:0)
您可以使用strstr
$break = "LIMIT";
$array = array();
$array[] = "WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT LIMIT, 121";
$array[] = "WHEN JOHN TRIED LIMIT 343, 333 HE FOUND";
echo "<pre>";
foreach ( $array as $value ) {
echo strstr($value, $break, true), PHP_EOL;
}
输出
WHEN JOHN WAS TRYING HIS SQL QUERY, HE FOUND THAT
WHEN JOHN TRIED