search

Home  >  Q&A  >  body text

php - How to regularly match the domain name in the middle of the URL

https://so.m.sm.cn/
https://m.sm.cn/
https://www.google.com/
https://m.sogou.com/
https://wap.sogou.com/
https://m.baidu.com/
https://www.google.fr/
https://wisd.sogou.com/

How to write the regular expression? I only want to extract the middle of these domain names, such as: baidu, sm, google, sogou

I can write https://m.sm.cn/ alone, but I can’t write https://so.m.sm.cn/ if I add this.
Help! ! !

淡淡烟草味淡淡烟草味2825 days ago561

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 13:12:17

    php doesn’t work, this is for python, this is just a reference. In other cases, think more on your own.

    import re
    
    pattern=re.compile(r'\.([^\.]*?)\.[^\.]*?$')
    a=re.findall(pattern,'www.ab.baidu.com')
    print a 
    #输出['baidu']

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:12:17

    preg_match('#://([\w\-\.]+)/?\b#',$string,$m) && $domain=$m[1];

    reply
    0
  • Cancelreply