2

我有一个字符串:

'This is some random text so you don't get upset [rethink]'

或者这个字符串

'This is some random text so you don't get upset [me] and [123]'

是否可以使用 TSQL 查找和替换 [text] 字符串?

结果:

'This is some random text so you don't get upset '

或者这个字符串

'This is some random text so you don't get upset  and '

编辑:

我已经修改了接受的答案,使函数更加动态:

CREATE FUNCTION [dbo].[StripTagWithChar]
(@TagLeft NVARCHAR(1),@TagText NVARCHAR(MAX),@TagRight NVARCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX(@TagLeft,@TagText)
    SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
    SET @Length = (@End - @Start) + 1

    WHILE (@Start > 0
        AND @End > 0
        AND @Length > 0)
    BEGIN
        SET @TagText = STUFF(@TagText,@Start,@Length,'')
        SET @Start = CHARINDEX(@TagLeft,@TagText)
        SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
        SET @Length = (@End - @Start) + 1
    END

    RETURN Replace(LTRIM(RTRIM(@TagText)),'  ',' ')
END

现在这个函数接受括号作为输入:

select [dbo].[StripTagWithChar]( '{' , 'this is {not} awesome' , '}' )

最酷的是,现在它将过滤带有相同括号的标签,如下所示:

select [dbo].[StripTagWithChar]( '=' , 'this is =not= awesome' , '=' )
4

1 回答 1

3

我建议对先前创建的去掉 HTML 标记的 UDF进行一些细微的修改......只需将<and>替换为[and ]

CREATE FUNCTION [dbo].[udf_StripTag]
(@TagText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('[',@TagText)
    SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
    SET @Length = (@End - @Start) + 1

    WHILE (@Start > 0
        AND @End > 0
        AND @Length > 0)
    BEGIN
        SET @TagText = STUFF(@TagText,@Start,@Length,'')
        SET @Start = CHARINDEX('[',@TagText)
        SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
        SET @Length = (@End - @Start) + 1
    END

    RETURN LTRIM(RTRIM(@TagText))
END
GO
于 2012-06-28T22:56:44.223 回答