Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a string separated by ',' in PHP

Tags:

string

regex

php

I have 2 types of string the first

"/css/style.min.css HTTP/1.1" 200 7832 index.php?firstId=5&secondid=4,6,8 HTTP/1.1"

the second type

"/css/style.min.css HTTP/1.1" 200 7832 /index.php?firstId=123&secondid=4,6,8" "Mozilla/5.0

i want to extract 4,6,8 with one code who works for all the case

i tried

$line = '/index.php?firstId=123&secondid=4,6,8" "Mozilla/5.0';
$nbpers = findme($line, 'secondid=', '"') ;

function findme($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

but it works just for the first case

i tried also this regex /.*?(\d+)$/ for finding the string who ends with numbers and i tested it in this site, but HTTP/1.1 ends with numbers so it was not a good idea

like image 219
parik Avatar asked Dec 20 '16 15:12

parik


2 Answers

You may extract all the comma-separated numbers after secondid= with

(?:\G(?!\A),|secondid=)\K\d+

See the regex demo.

Details:

  • (?:\G(?!\A),|secondid=) - match either the end of the previous successful match and a , (see \G(?!\A),) or (|) a secondid= substring
  • \K - omit the whole text matched so far
  • \d+ - 1 or more digits

See the PHP demo:

$s = '"/css/style.min.css HTTP/1.1" 200 7832 /index.php?firstId=123&secondid=4,6,8" "Mozilla/5.0';
preg_match_all('~(?:\G(?!\A),|secondid=)\K\d+~', $s, $results);
print_r($results[0]);
like image 119
Wiktor Stribiżew Avatar answered Oct 04 '22 16:10

Wiktor Stribiżew


To me this reads like you want to extract the full substring 4,6,8. If so, why not simply use a capturing group to extract the part after secondid= like in this regex101 demo.

preg_match('/\bsecondid=([\d,]+)/', $string, $out)
  • \b matches a word boundary
  • ( capturing group ) for part to extract
  • \d is a short for digit [0-9]

See your updated code sample at eval.in. If needed, you can still return the exploded part.

like image 36
bobble bubble Avatar answered Oct 04 '22 17:10

bobble bubble