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查詢。
你打我。關於發佈相同的東西。 – BlitZ 2014-08-29 09:16:39
我需要str_replace URL中的「/」才能逃脫LIKE的「\ /」版本嗎? – user3143218 2014-08-29 09:17:51
@ user3143218可能,沒有。 – BlitZ 2014-08-29 09:18:33