![](/img/trans.png)
[英]How to use regular expressions to extract the term inbetween the square brackets in PHP?
[英]How to use regular expressions in php to extract data like this?
我在php中使用以下代碼提取用戶名,密碼和電子郵件:
$subject = "fjcljt # 123456789 # chengyong702@126.com";
$pattern2 = '/^(\w+\ # ){2}?\w+ ?/';
preg_match($pattern2, $subject, $matches);
但是使用print_r返回的結果是Array ( [0] => fjcljt # 123456789 # chengyong702 [1] => 123456789 # )
我在這里preg_match做錯了什么?
如果“#”分隔了您的值...根本不需要正則表達式...
$subject = "fjcljt # 123456789 # chengyong702@126.com";
$subject = array_map('trim',explode("#",$subject));
preg_match
的結果捕獲[0]
的整個字符串,然后捕獲[i]
每個捕獲組。 捕獲的組由$pattern2
的方括號表示。 由於只有一組括號,因此只有一個被捕獲的組。
即使您的模式匹配兩次,也只有最新的匹配存儲在組1中,即123456789 #
(覆蓋fjcljt #
)。
要獲取顯式組,您必須在正則表達式中顯式編寫捕獲的組,而不是使用{2}
:
$pattern2 = '/^(\w+\ # )(\w+\ # )\w+ ?/';
然后,您的返回數組將具有[1]
fjcljt #
和[2] being 1123456789 #
。
list($username, $password, $email) = explode(' # ', $subject);
嘗試使用explode而不是regex。 正則表達式使用更多資源。
$ data = explode('#','fjcljt#123456789#chengyong702@126.com');
那么您可以訪問如下數據:
$ data [0]; //用戶名
$ data [1]; //密碼
$ data [2]; //電子郵件
編輯空格使用分隔符,如下所示:
“#”
這是兩件事。 首先,您要在匹配組(..)
上使用量詞{2}
。 發生的情況是,您只獲得了兩個匹配項中的最后一個作為結果組[1]
。 如果要分別獲得兩個數字/單詞,則必須擴展正則表達式。
第二個問題是\\w+
不包含@
。 因此,您只會收到一半的電子郵件。
$pattern2 = '/^(\w+) # (\w+) # ([\w@.]+)/';
可能是您想要的。
不確定您嘗試使用的F炸彈是什么,但是如果您嘗試獲取登錄憑據,則可以嘗試這樣的操作
if(preg_match('/^.*\@.*$/i', $type_of_login) > 0)
{
$request = User::get_by_email($type_of_login);
}
else
{
//get by username or whatevers....
}
//then extract the password!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.