2012-04-19 81 views
2

我試圖href屬性是從數據庫中來大量文本內替換破折號下劃線內:試圖取代下劃線_與破折號 - 一個href標籤

現有文本:

Hello, my name is <a href="http://example.com/joe_smith">joe smith</a> and I 
eat pizza with my friend <a href="http://example.com/john_doe">john doe</a>. 

輸出:

Hello, my name is <a href="http://example.com/joe-smith">joe smith</a> and I 
eat pizza with my friend <a href="http://example.com/john-doe">john doe</a>. 

因爲它是目前在MySQL數據庫中,我認爲這將是更快,如果我可以使用SQL語句執行的操作,但如果那是不可能的我想用php正則表達式來做。

我不想以某種原因替換常規文本中的下劃線。只有href內的那些。

回答

3

MySQL的正則表達式僅用於搜索。他們根本不支持替換。您可以使用它們來查找需要修復的記錄,但是僅限於mysql中的基本字符串操作,僅用於實際更改記錄。

你最好將匹配的記錄拉入PHP並在那裏進行更改。哪一個當然然後提出在html上使用正則表達式...不要這樣做。使用PHP的DOM代替實際的操作。

0
(<a href=".+?)_(.+?">) 

隨着更換

$1-$2 
1

你可以用1個更新SQL查詢做到這一點。我準備了一張測試表,並更新查詢來演示。 基本上在你自己的表上使用,只需將表名從TestTable更改爲你的表名,並將「Field」的名稱更改爲你想要更新的字段名。

如果在一個字段中有多個href鏈接。您需要多次執行查詢。 您可以在第一次查詢時在表格中找到最大的鏈接發生次數。執行更新查詢多次。當你在occurence_count的計數上更新你的查詢時,我比你更清楚地提供了一些我用來清除一些臨時數據的查詢。

- 找到最大鏈路出現次數在表

SELECT max(cast((LENGTH(Field) - LENGTH(REPLACE(Field, '<a href', '')))/7 as unsigned)) AS occurrence_count 
FROM TestTable; 

- 更新表格occurrence_count次更換所有A HREF鏈接。

update TestTable 
set Field = replace 
       (
        @b:=replace 
        (
        @a:=replace(Field 
         , substring(Field, Instr(Field, "<a href='"), Instr(Field, "</a>")-Instr(Field, "<a href='")+4) 
         , replace(substring(Field, Instr(Field, "<a href='"), Instr(Field, "</a>")-Instr(Field, "<a href='")+4), "_", "-") 
        ) 
        , substring(@a, Instr(@a, "<a href='"), Instr(@a, "</a>")-Instr(@a, "<a href='")+4) 
        , replace(substring(@a, Instr(@a, "<a href='"), Instr(@a, "</a>")-Instr(@a, "<a href='")+4), "<a href=", "<*a href=") 
        ) 
       , substring(@b, Instr(@b, "<*a href='"), Instr(@b, "</a>")-Instr(@b, "<*a href='")+4) 
       , replace(substring(@b, Instr(@b, "<*a href='"), Instr(@b, "</a>")-Instr(@b, "<*a href='")+4), "</a>", "</*a>") 
       ) 
; 

- 一旦運行這個當你所有的更新完成從A HREF鏈接清除星星。

update TestTable set Field = replace(replace(Field, "<*a href", "<a href"), "</*a>", "</a>") 

- 檢查你的表

select * from TestTable; 

測試表

CREATE TABLE `testtable` (
    `id` INT(11) NOT NULL AUTO_INCREMENT, 
    `Field` VARCHAR(255) NOT NULL DEFAULT '', 
    PRIMARY KEY (`id`) 
) 
COLLATE='latin1_swedish_ci' 
ENGINE=MyISAM 
ROW_FORMAT=DEFAULT 

測試數據

Insert into TestTable (Field) values ("Hello, my name is <a href='http://example.com/joe_smith'>joe smith</a> and I eat pizza with my friend <a href='http://example.com/john_doe'>john doe</a>"); 
Insert into TestTable (Field) values ("Hello, my name is <a href='http://example.com/joe_smith'>joe smith</a> and I eat pizza with my friend <a href='http://example.com/john_doe'>john doe</a> my friend <a href='http://example.com/john_doe'>jane doe</a>"); 
相關問題