【问题标题】:php using preg_replace to turn urls into links..... sometimes.... :P [duplicate]php 使用 preg_replace 将网址转换为链接.....有时....:P [重复]
【发布时间】:2012-03-10 22:00:40
【问题描述】:

可能重复:
How to add anchor tag to a URL from text input
PHP Regular expression to match keyword outside HTML tag <a>

好的,所以我正在使用 OsTicket(电子邮件票证系统),并将其转换为使用 HTML 格式的电子邮件进出。它被黑了,但它可以工作。

好吧,目前那里有一个名为“clickableURLS”的函数......

  function clickableurls($text) {

        //Not perfect but it works - please help improve it. 
        $text=preg_replace('/([^(\'|")]((f|ht){1}tp(s?):\/\/)[-a-zA-Z0-9@:%_\+.~#?&;\/\/=]+[^(\'|")])/','<a href="\\1" target="_blank">\\1</a>', $text);
        $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")]www\.([a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(\/[^\/ \\n\\r]*)*[^('|\")])/",
                '\\1<a href="http://\\2" target="_blank">\\2</a>', $text);
        $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")][_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}[^('|\")])/",'\\1<a href="mailto:\\2" target="_blank">\\2</a>', $text);


        return $text;
    }

如您所见,它基本上需要一个 URL(搜索 http 或 https 或 www),然后在其中添加适当的 mumbo jumbo。

嗯....

我现在设置了 WYSIWYG....所以如果我们的一位技术人员使用 WYSIWYG 以正确的方式创建链接...自动创建代码...。那么 clickableurls 函数也可以找到http 已经在文本中并再次将其转换...

所以我基本上是想找出处理这个问题的最佳方法。我确实想要两个选项.. 并且正在考虑可能会做一个 IF 语句,但是更改 preg_replace 不会更有意义吗?

有什么想法吗?再次感谢溢出社区!

【问题讨论】:

  • 你的正则表达式有问题。在不知道具体细节的情况下很难为您提供帮助。
  • 搜索“Linkify URL”——那里有很多答案! (Here's the one I use)。

标签: php regex preg-replace


【解决方案1】:

我可以帮助您翻译第一个 preg_replace() 正则表达式中的内容。
这是我能做的最好的事情,因为我不知道你的意图。我已经推断出一些意图,
但由您决定。

当正则表达式很复杂时,块格式有助于轻松查看复杂性。

([^(\'|")]((f|ht){1}tp(s?):\/\/)[-a-zA-Z0-9@:%_\+.~#?&amp;;\/\/=]+[^(\'|")])

(                                    # Capture group 1
    [^'"]                                # Consume a character that is not single nor double quote
    (                                    # Capture group 2
      (?:ftp|https?):                       # Either ftp, OR http (optional s) string literal
      //                                    # Literl double forward shashes
    )                                    # End capt grp 2
    [-a-zA-Z0-9@:%_+.~#?&;/=]+           # 1 or more (greedy) of the characters in this class
    [^'"]                                # Consume a character that is not single nor double quote
)                                    # End capt grp 1

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多