替换MySQL的URL模式

use*_*218 1 php regex mysql

我试图弄清楚如何在MySQL列上使用正则表达式搜索来更新一些数据.

问题是我正在尝试重命名URL的一部分(即目录).

该表看起来像这样(虽然它只是一个例子,实际数据是任意的):

myTable的:

| 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  |
Run Code Online (Sandbox Code Playgroud)

我需要将所有具有"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  |
Run Code Online (Sandbox Code Playgroud)

目前,我唯一可以弄清楚如何做的方法是使用正则表达式quires的组合来检查目录,然后循环它并更改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));
}
Run Code Online (Sandbox Code Playgroud)

这似乎工作得很好,但是如果有一个大表,它可能会非常重视性能.

我想知道是否有更有效的方法来做到这一点?也许在mySQL查询中使用某种正则表达式替换.

hjp*_*r92 5

只需使用该REPLACE()功能:

UPDATE myTable
SET URL = REPLACE(url, 'path/to/Directory/', 'path/to/anotherDirectory/')
WHERE URL LIKE '%path/to/Directory/%'
Run Code Online (Sandbox Code Playgroud)

  • @ user3143218可能,没有. (2认同)