如何使用 PHP 来识别(而不是验证)URL

How to use PHP to recognising (and not validating) URL

我知道 filter_var() 并且它是 FILTER_VALIDATE_URL 过滤器。关键是有一些 URL 存在但不算作有效 URL,我需要验证它们。例如,URLs 带空格。

目前我只检查应用程序感兴趣的那些协议(http、https 和 ftp)使用 strpos()

但我想知道 PHP 中是否有我可以使用的更通用的方法?

如果我解释我需要区分目标源是 URL 还是本地路径,这可能会有所帮助。

使用函数 parse_url() 将 URL 拆分成组件,然后对其进行一些基本分析 returns (或者只是检查返回值是否为 array()FALSE).

如文档所述:

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

还有:

On seriously malformed URLs, parse_url() may return FALSE.

看起来很符合你的要求。