开发者

Regular Expressions and php

开发者 https://www.devze.com 2022-12-12 01:11 出处:网络
I have a form where users e开发者_运维问答nter a URL. I need a regular expression to skip the part \'http://\' if present. For example, if the user insert into the form: http://youtube.com I need to s

I have a form where users e开发者_运维问答nter a URL. I need a regular expression to skip the part 'http://' if present. For example, if the user insert into the form: http://youtube.com I need to save only youtube.com. I don't know regular expressions. Could you help me? Thanks!


I think maybe a regular expression would be overkill here. How about this?

$str = str_replace(array('http://', 'https://'),'',$str);


Please keep in mind, that the string http:// could occur twice or more times in an URL!

$parts = parse_url('http://youtube.com');
$url   = $parts['host'].$parts['path']; //.'?'.$parts['query'].'#'.$parts['fragment']

See parse_url()


You do not really need regular expressions. This would be enough:

if (substr($str, 0, 7) == 'http://')
    $str = substr($str, 7);
else if (substr($str, 0, 8) == 'https://')
    $str = substr($str, 8);

EDIT: Added the else if part.


You could just use substr to check if the string begins with 'http://' and remove that part; no regex.


you could do it without a regex, since you don't know regexes, and just check if the index of the first found "http://" string (case insensitive) is at position 0, and if it is remove it.


Not needed. However, if you want regex:

// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', $the_url, $matches);
$host = $matches[1];
0

精彩评论

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