How to find string separated by ',' in PHP

I have 2 types of lines first

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

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 one code that works for the whole 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 only works for the first case

I also tried this regex /.*?(\d+)$/ to search for a string that ends with numbers, and I tested it on this site, but HTTP/1.1 ends with numbers, so this was not a good idea

+5
source share
2 answers

You can extract all numbers separated by commas after secondid= with

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

See the demo of regex .

More details

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

See the demo version of PHP :

 $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]); 
+6
source

It reads to me as if you want to extract the full substring 4,6,8 . If so, why not just use the group to extract the part after secondid= , as in this demo version of regex101 .

 preg_match('/\bsecondid=([\d,]+)/', $string, $out) 

See the updated code sample in eval.in. If necessary, you can return the detonated part .

+2
source

Source: https://habr.com/ru/post/1261575/


All Articles