I have a string:
'This is some random text so you don't get upset [rethink]'
or this string
'This is some random text so you don't get upset [me] and [123]'
Is it possible using TSQL to find and replace the [text] strings?
The result:
'This is some random text so you don't get upset '
or this string
'This is some random text so you don't get upset and '
EDIT:
I have modified the accepted answer so that the function to be more dynamic:
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
Now this function accepts the enclosing brackets as an input:
select [dbo].[StripTagWithChar]( '{' , 'this is {not} awesome' , '}' )
And the most cool thing is that now it will filter tags with identical brackets like this:
select [dbo].[StripTagWithChar]( '=' , 'this is =not= awesome' , '=' )
I would suggest making some slight modifications to a previously created UDF that strips out HTML tags… simply replace the
<and>with[and]: