我试图从insert语句的粘贴中提取一些工作,并将它们格式化为mysqli准备的语句。
下面是一个例子:
INSERT INTO
products
(hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7],[value-8],[value-9],[value-10],[value-11],[value-12],[value-13])
所以我尝试了一个正则表达式:
find: (\[.*)(])
replace: ?
但是,它不是替换每个[value=*]
,而是只在结束括号的最后一个实例处替换它们。为什么?
产出:
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
(?)
我怎么才能把它换好。我的regex不应该选择所有直到第一个结束括号,但为什么它选择所有直到最后结束括号?
发布于 2014-08-30 00:27:38
*
是一个greedy操作符,这意味着它将尽可能多地匹配,并且仍然允许正则表达式的其余部分匹配。使用*?
进行非贪婪匹配,意思是“零或更多-最好尽可能少”。
(\[.*?)(])
注意事项:没有必要使用捕获组,因为在替换调用中没有引用它们。
Find: \[.*?\]
Replace: ?
发布于 2014-08-30 00:27:10
不要忘记*
是贪婪的,它试图尽可能地匹配,而是使用非贪婪的版本:
(\[.*?)(])
发布于 2014-08-30 00:54:23
正如其他人所说的,*
是贪婪的,而*?
是非贪婪的,并且只会获得匹配的最小数量(这就是您想要做的)。
但是,与其为PHP设置一系列问号和逗号,不如懒惰地让PHP自己生成它们:implode(',', array_fill(0, 13, '?'))
。
不管你需要多少饲料来代替那个13
,你就有了一组可靠的占位符,不太容易出现交叉眼的排字。
示例:
$placeholders = implode(',', array_fill(0, 13, '?'));
$sql = <<<SQL
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
($placeholders)
SQL;
echo $sql
**:**
INSERT INTO
products
(id, hash, name, description, large_img, small_img, label_img, category, small, large, small_price, large_price, best_seller, in_stock)
VALUES
(?,?,?,?,?,?,?,?,?,?,?,?,?)
https://stackoverflow.com/questions/25577835
复制相似问题