2012-04-19 82 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>"); 
相关问题