Search code examples
phpregexsubstrcsv

How to extract an ID number from a string?


How do I retrieve the middle value using regex or preg_match?

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'

How do I only get values ​​from ds_user_id using regex or preg_match?


Solution

  • Use preg_match to match ds_user_id=, then forget those matched characters with \K, then match one or more digits. No capture groups, no lookarounds, no parsing all the key-value pairs, no exploding.

    Code: (Demo)

    $str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';
    echo preg_match('~ds_user_id=\K\d+~', $str, $out) ? $out[0] : 'no match';
    

    Output:

    219132