哪些字符使URL无效?

这些url是否有效?

example.com/file [/] . html http://example.com/file [/] . html


当前回答

我提出了一些PHP正则表达式,可以将文本中的url转换为锚标记。(首先它转换所有的www。url到http://,,然后转换所有的url与https?:// to a href=…HTML链接

美元管柱= preg_replace (' / (https ?:\/\/)([!#$&-;=?\-\[\]_ a - z ~ %] +) / sim’,'“$ 1 $ 2”< a href = > $ 2 < / a > ', preg_replace(' /(±s) ( \.)([!#$&-;=?\-\[\]_ a - z ~ %] +) / sim’' $ 1http: / / $, $管柱));

其他回答

这并不是对你的问题的真正答案,但验证URL确实是一个严肃的p.i.t.a。你可能最好验证域名,并留下URL的查询部分。这是我的经验。

您还可以通过ping URL来查看它是否会得到一个有效的响应,但是对于这样一个简单的任务来说,这可能有点太过了。

正则表达式检测url是丰富的,谷歌它:)

所有可以在URI中使用的有效字符(URL是URI的一种类型)都在RFC 3986中定义。

所有其他字符都可以在URL中使用,只要它们是“URL编码”的。这涉及为特定的“代码”更改无效字符(通常是百分号(%)后面跟着十六进制数的形式)。

此链接HTML URL Encoding Reference包含无效字符的编码列表。

我需要选择字符来分割字符串中的URL,所以我决定创建一个字符列表,这些字符无法在URL中自己找到:

>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'

因此,可能的选择是换行符、制表符、空格、反斜杠和“<>{}^|”。我想我还是用空格或者换行吧。:)

来源(需要时加强调):

Unsafe: Characters can be unsafe for a number of reasons. The space character is unsafe because significant spaces may disappear and insignificant spaces may be introduced when URLs are transcribed or typeset or subjected to the treatment of word-processing programs. The characters "<" and ">" are unsafe because they are used as the delimiters around URLs in free text; the quote mark (""") is used to delimit URLs in some systems. The character "#" is unsafe and should always be encoded because it is used in World Wide Web and in other systems to delimit a URL from a fragment/anchor identifier that might follow it. The character "%" is unsafe because it is used for encodings of other characters. Other characters are unsafe because gateways and other transport agents are known to sometimes modify such characters. These characters are "{", "}", "|", "", "^", "~", "[", "]", and "`". All unsafe characters must always be encoded within a URL. For example, the character "#" must be encoded within URLs even in systems that do not normally deal with fragment or anchor identifiers, so that if the URL is copied into another system that does use them, it will not be necessary to change the URL encoding. Source

我不能评论以上的答案,但我想强调的是,并非所有地方都允许使用允许的字符。例如,域名不能有下划线,因此http://test_url.com无效。