2014-08-29 55 views
1

我想弄清楚如何在MySQL列上使用正则表达式来更新一些数据。替换MySQL的URL模式

问题是我想重命名一部分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 | 

我需要替换所有具有“路径/到网址/ Directory /“改为”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 | 

此刻,我能弄清楚它是如何使用正则表达式奎雷斯的组合来检查目录做的唯一途径,这样的

$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)); 
} 

这似乎是工作得很好,但是有一个大表也可以是性能相当沉重:然后遍历并更改URL,像这样。

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

回答

4

只需使用REPLACE()功能:

UPDATE myTable 
SET URL = REPLACE(url, 'path/to/Directory/', 'path/to/anotherDirectory/') 
WHERE URL LIKE '%path/to/Directory/%' 
+0

你打我。关于发布相同的东西。 – BlitZ 2014-08-29 09:16:39

+0

我需要str_replace URL中的“/”才能逃脱LIKE的“\ /”版本吗? – user3143218 2014-08-29 09:17:51

+2

@ user3143218可能,没有。 – BlitZ 2014-08-29 09:18:33