确定用户输入包含URL

Determine User Input Contains URL

本文关键字:包含 URL 输入 用户      更新时间:2023-09-26

我有一个收集混合字符串的输入表单字段。

确定张贴的字符串是否包含URL(例如http://link.com, link.com, www.link.com等),以便可以根据需要正确锚定。

这方面的一个例子是微博功能,其中处理脚本将锚定任何链接。其他示例可能是相同的帖子,其中"http://link.com"被自动锚定。

我认为我应该在显示而不是输入中处理这个问题。我该怎么做呢?

您可以使用正则表达式在PHP中的每个匹配上调用函数。例如,你可以这样写:

<?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模式。PHP提供了一个名为preg_match的函数,它允许您这样做。

正则表达式本身可以有几种形式,但这里有一些东西可以让你开始(也可能只是谷歌'URL regex':

'/^ (((http | https | ftp)://) ? ([[a-zA-Z0-9 ]-.])+(.)([[ a-zA-Z0-9]]) {2,4} ([[a-zA-Z0-9]/+ = %, _。~ ? -])) $/'

所以你的代码应该是这样的:
$matches  = array(); // will hold the results of the regular expression match
$string   = "http://www.astringwithaurl.com";
$regexUrl = '/^(((http|https|ftp):'/'/)?([[a-zA-Z0-9]'-'.])+('.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]'/+=%&_'.~?'-]*))*$/';
preg_match($regexUrl, $string, $matches);
print_r($matches); // an array of matched patterns

从这里开始,你只需要在锚/href标签中包装这些URL模式,你就完成了。

你想要多精确?考虑到url的多样性,您必须在某个地方划清界限。例如。

www.ca是一个完全有效的主机名,并带来了一个网站,但它不是你所期望的工作。

您应该为此研究正则表达式。

您将构建一个模式,该模式将匹配字符串中看起来像URL的部分,并对其进行适当的格式化。

结果是这样的(取消了这个,还没有测试过);

$pattern = "((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(''''))+['w'd:#@%/;$()~_?'+-='''.&]*)";
preg_match($pattern, $input_string, $url_matches, PREG_OFFSET_CAPTURE, 3);

$url_matches将包含输入字符串中与url模式匹配的所有部分的数组。

可以使用$_SERVER['HTTP_HOST']获取主机信息。

<?php
$host = $SERVER['HTTP_HOST'];
 ?>

  <a href ="<?= $host ?>/post.html">Post</a>