php - 替换 MySQL 的 URL 模式

标签 php mysql regex

我正在尝试弄清楚如何在 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/

相关文章:

php - 删除页面不起作用

php - 如何减去两个日期和时间以获得差异

mysql - 错误: Error 1022: Can't write; duplicate key in table 'recipes'

php - 等效于 PHP 中的 escape(window.location.href)

javascript - URL 不会传递来自 ajax 输入的第二个 "select"值

mysql - Rails 部署期间的 "error 28 from storage engine"

mysql - 为什么我不能在 MySQL 的索引 0 处插入一行?

regex - 如何在 Elixir 中操作正则表达式替换字符串

java - 正则表达式拆分字符串(在 Java 中)以便保留空格?

javascript - 用于仅匹配和替换 excel 公式字符串中的列号数字的正则表达式