search

Home  >  Q&A  >  body text

PHP regular intercepts the content after the domain name in the URL

php program
needs to match the beginning of http:// or https://, retain the domain name, and intercept the content after the domain name
For example, http://www.baidu.com/aa/bbb only needs http ://www.baidu.com intercept /aa/bbb

phpcn_u1582phpcn_u15822780 days ago1089

reply all(5)I'll reply

  • 某草草

    某草草2017-05-16 13:16:30

    You don’t have to use regular rules to be generous. Isn’t this more elegant?

    $url = 'http://www.baidu.com/aa/bbb';
    var_dump(parse_url($url));
    //array(3) {
         ["scheme"]=> string(4) "http" 
         ["host"]=> string(13) "www.baidu.com" 
         ["path"]=> string(7) "/aa/bbb"
        }

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:16:30

    if(strncmp('http://', $url, 7) === 0 || strncmp('https://', $url, 8)) {
      $host = substr($url, strpos($url, '/', strncmp('http://', $url, 7) ? 8 : 7));
    } else {
      $host = null;
    }

    If possible, try not to use regular expressions

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:16:30

    There are many methods for this. Since the requirement is regular, please see the code below

        $str= 'http://www.baidu.com/aa/bbb';
        $patten = '/(http[s]?:\/\/\w*.\w*.\w*\/).*/';
        preg_match($patten, $str, $match);
    
        echo $match[1];

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:16:30

    https://www.bytelang.com/o/s/...

    Refer to the answers below

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:16:30

    Isn’t it better to use explode? Why use regular expressions

    reply
    0
  • Cancelreply