[英]extracting data between [ ] with preg_match php
我嘗試從我的響應文本文件中僅提取[]之間的數字:
$res1 = "MESSAGE_RESOURCE_CREATED Resource [realestate] with id [75739528] has been created.";
我用這個代碼
$regex = '/\[(.*)\]/s';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1];
我的結果是:
realestate] with id [75742084
有人能幫我嗎 ?
用這個:
$regex = '~\[\K\d+~';
if (preg_match($regex, $res1 , $m)) {
$thematch = $m[0];
// matches 75739528
}
在正則表達式演示中查看比賽。
說明
\\[
匹配左括號 \\K
告訴引擎放棄與最終匹配相距甚遠的匹配,它返回 \\d+
匹配一個或多個數字 您的正則表達式將是
(?<=\[)\d+(?=\])
PHP代碼是
$regex = '~(?<=\[)\d+(?=\])~';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[0];
輸出:
75739528
我假設您想匹配方括號內的內容,這意味着您必須匹配除方括號外的所有內容:
/\[([^]]+)\]/g
忽略preg_match()
的g標志:
$regex = '/\[([^]]+)\]/';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1]; //will output realestate
echo $matches_arr[2]; //will output 75739528
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.