我正在尝试弄清楚如何在 MySQL 列上使用正则表达式搜索来更新一些数据。
问题是我正在尝试重命名 URL 的一部分(即目录)。
表格看起来是这样的(虽然只是一个例子,实际数据是任意的):
我的表:
| user_name | URL |
| ------------- |:---------------------------------------------------------:|
| John | http://example.com/path/to/Directory/something/something |
| Jane | http://example.com/path/to/Directory/something/else |
| Jeff | http://example.com/path/to/Directory/something/imgae.jpg |
我需要将所有具有“path/to/Directory/”的 URL 替换为“path/to/anotherDirectory/”,同时保持 URL 的其余部分不变。
所以更新后的结果应该是这样的:
| user_name | URL |
| ------------- |:----------------------------------------------------------------:|
| John | http://example.com/path/to/anotherDirectory/something/something |
| Jane | http://example.com/path/to/anotherDirectory/something/else |
| Jeff | http://example.com/path/to/anotherDirectory/something/imgae.jpg |
目前,我能弄清楚如何做到这一点的唯一方法是使用正则表达式组合来检查目录,然后遍历它并更改 URL,如下所示:
$changeArr = $db->query("SELECT URL FROM myTable WHERE URL REGEXP 'path/to/Directory/.+'");
$URLtoChange = "path/to/Directory/";
$replace = "path/to/anotherDirectory/"
foreach ($changeArr as $URL) {
$replace = str_replace($URLtoChange, $replace, $URL);
$db->query("UPDATE myTable SET URL = :newURL WHERE URL = :URL", array("URL"=>$URL,"newURL"=>$replace));
}
这似乎工作得很好,但是对于一个大表来说,它可能会对性能造成很大的影响。
我想知道是否有更有效的方法来做到这一点?也许在 mySQL 查询中使用某种正则表达式替换。
最佳答案
只需使用 REPLACE()
功能:
UPDATE myTable
SET URL = REPLACE(url, 'path/to/Directory/', 'path/to/anotherDirectory/')
WHERE URL LIKE '%path/to/Directory/%'
关于php - 替换 MySQL 的 URL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25565189/