开发者

simple question about preg_match() in php

i used bellow code to search and find if http is includes in $url address user enters

if (!preg_开发者_运维问答match("/http:///", $user_website) 

but i got this error

Warning: preg_match() [function.preg-match]: Unknown modifier '/' in

i know its becuase of // of http but how work arround this !?


Instead of having to escape every / in URL regexes it's often useful to use preg_* alternative characters to mark the start/end of the pattern.

if (!preg_match("#http://#", $user_website)


The delimiter you are using / is found in the pattern as well. In such cases you can either escape the delimiter in the pattern:

if (!preg_match("/http:\/\//", $user_website) 

or you can choose a different delimiter. This will keep the pattern clean and short:

if (!preg_match("#http://#", $user_website) 


You can escape the slashes like the other answers mention, or alternatively you can use different delimiters, preferably characters you won't use in your regex:

preg_match('~http://~', ...)
preg_match('!http://!', ...)

And you don't really need regex for this. String matching should be enough:

if (strpos($user_website, 'http://') !== false) {
    // do something
}

See: strpos()


Surely you must do

$parts = parse_url($my_url);

$parts['scheme'] will then contain the url scheme (might be 'http').


Escape / characters with \ characters.


You need to escape literal characters. Place a back-slash before your forward slashes.

http:// becomes http:\/\/


if (!preg_match("/http:\/\//", $user_website) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜