簡體   English   中英

用preg_match php在[]之間提取數據

[英]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+(?=\])

DEMO

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.

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