【问题标题】:How to replace URL text in <a href>.. string? [closed]如何替换 <a href>.. 字符串中的 URL 文本? [关闭]
【发布时间】:2023-03-27 08:30:01
【问题描述】:

我的 SQL Server 2012 在数据类型为nvarchar(max) 的列comments 中有一些数据。

样本数据:

For more information, please visit www.sample.com 
If you desire submit a request please go here: www.request.com
Customer Service.

我需要得到这个:

For more information, please visit <a href="www.sample.com">www.sample.com</a> 
If you desire submit a request please go here: <a href="www.request.com">www.request.com</a>
Customer Service."

所有链接都以www 开头。感谢您的帮助

【问题讨论】:

  • 只使用 SQL 有什么需要?使用任何编程语言(如 C#、Java 等)都可以轻松实现。我可以给你一个 C# 解决方案。
  • @henpat- 你想要 sql 行中的 html 控件吗?
  • 因此,您可以使用一些正则表达式检查“单词”是否以 www 开头并以单词或数字和点结尾并以两三个或四个字母结尾。我认为正则表达式是你应该探索的东西。
  • @Trond 虽然可能还有更多的情况需要处理:data.site.co.ukhttp://google.com,所以不太可能这么简单。
  • Google 并了解 SQL 中的 PATINDEX() 和 SUBSTRING() 函数。这是一个简单的编程问题。

标签: sql sql-server url replace href


【解决方案1】:

您可以创建一个这样的函数,接收原始字符串,然后返回带有 html 的结果:

CREATE FUNCTION dbo.ufnUrlHref (
    @str nvarchar(max)
)

RETURNS nvarchar(max)
AS
BEGIN

DECLARE @nextMatch int = patindex('%www.%', @str); --find start of next 'www.'
DECLARE @result nvarchar(max) = '';

WHILE (@nextMatch != 0)
BEGIN
    DECLARE @matchEnd int = charindex(' ', @str, @nextMatch);
    DECLARE @strLen int = len(@str);
    DECLARE @first nvarchar(max) = substring(@str, 1, @strLen - (@strLen - @matchEnd)); --get all of string up to first url
    DECLARE @last nvarchar(max) = substring(@str, @matchEnd + 1, @strLen - @matchEnd); --get rest of string after first url
    DECLARE @url nvarchar(255) = substring(@str, @nextMatch, @matchEnd - @nextMatch); --get url
    SET @first = replace(@first, @url, '<a href="' + @url + '">' + @url + '</a>'); --replace url w/ full href
    SET @result = @result + @first; --add updated string to result

    --set up for next run
    SET @str = @last; --remove corrected section from string
    SET @nextMatch = patindex('%www.%', @str); --find start of next 'www.'
END --end while

IF @str IS NOT NULL --add any remaining text back into result
BEGIN
    SET @result = @result + @str;
END

RETURN @result;

END;

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多