我有一个收集混合字符串的输入表单字段。
确定发布的字符串是否包含 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);
}
?>
关于php - 确定用户输入包含 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6984213/