簡體   English   中英

PHP的preg_match網址正則表達式不起作用

[英]php preg_match url regex not working

我無法正常運行此功能:

function isValidURL($url){
 return preg_match('%http://domain\.com/([A-Za-z0-9.-_]+)/([A-Za-z0-9.-_]+)%', $url);
}

網址:

http://domain.com/anything-12/anything-12/

可以包含數字,字母和符號_-

我認為這與第一個正則表達式有關-這些工作

    http://domain.com/anything12/anything12/

    http://domain.com/anything12/anything-12/

    http://domain.com/anything12/any-thing-12/

    http://domain.com/anything_12/any-thing-12/

一如既往地感謝所有幫助,並在此先感謝。

  1. 您需要在正則表達式的字符類中轉義-

  2. 您需要錨定正則表達式,以便嘗試匹配整個輸入字符串而不是其中的一部分。

修改后的正則表達式為:

'%^http://domain\.com/([A-Za-z0-9.\-_]+)/([A-Za-z0-9.\-_]+)/$%'

您可以通過注意[A-Za-z0-9_]\\w相同來縮短正則表達式,並且還有重復的子正則表達式。

'%^http://domain\.com(/[\w.-]+){2}/$%'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM