确定用户输入包含URL [英] Determine User Input Contains URL

查看:72
本文介绍了确定用户输入包含URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入表单字段,用于收集混合字符串.

I have a input form field which collects mixed strings.

确定发布的字符串是否包含URL(例如 http://link.com , link.com,www.link.com等),以便随后可以根据需要将其正确锚定.

Determine if a posted string contains an URL (e.g. http://link.com, link.com, www.link.com, etc) so it can then be anchored properly as needed.

一个例子就是微博客功能,其中处理脚本将使用链接锚定任何内容.其他示例可能是同一帖子,其中"http://link.com"自动定位.

An example of this would be something as micro blogging functionality where processing script will anchor anything with a link. Other sample could be this same post where 'http://link.com' got anchored automatically.

我相信我应该在展示而不是在输入时进行处理.我该怎么办?

I believe I should approach this on display and not on input. How could I go about it?

推荐答案

您可以使用正则表达式在PHP中的每个匹配项上调用一个函数.例如,您可以使用以下内容:

You can use regular expressions to call a function on every match in PHP. You can for example use something like this:

<?php

function makeLink($match) {
    // Parse link.
     $substr = substr($match, 0, 6);
     if ($substr != 'http:/' && $substr != 'https:' && $substr != 'ftp://' && $substr != 'news:/' && $substr != 'file:/') {
        $url = 'http://' . $match;
     } else {
        $url = $match;
     }

     return '<a href="' . $url . '">' . $match . '</a>';
}
function makeHyperlinks($text) {
    // Find links and call the makeLink() function on them.
    return preg_replace('/((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/e', "makeLink('$1')", $text);
}

?>

这篇关于确定用户输入包含URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆