2016-12-20 6 views
5

में ',' द्वारा अलग मैं स्ट्रिंग पहलेकैसे एक स्ट्रिंग पीएचपी

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

दूसरे प्रकार

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

मैं एक के साथ4,6,8 निकालना चाहते हैं के 2 प्रकार है खोजने के लिए कोड जो सभी मामलों के लिए काम करता है

मैंने

की कोशिश की
$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); 
} 

लेकिन यह सिर्फ पहला मामला

मैं भी स्ट्रिंग जो संख्या के साथ समाप्त होता है खोजने के लिए इस regex /.*?(\d+)$/ की कोशिश की और मैं इस साइट में इसका परीक्षण किया के लिए काम करता है, लेकिन HTTP/1.1 संख्या के साथ समाप्त होता है तो यह एक अच्छा नहीं था विचार

उत्तर

6

आप

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

साथ secondid= के बाद सभी अल्पविराम से अलग संख्या निकाल सकते हैं regex demo देखें।

विवरण:

  • (?:\G(?!\A),|secondid=) - तो मिलान किया पूरे पाठ को छोड़ देते हैं - पिछले सफल मैच के दोनों छोर और एक , (\G(?!\A), देखें) या (|) एक secondid= सबस्ट्रिंग
  • \K से मेल खाते हैं दूर
  • \d+ - 1 या अधिक अंक

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]); 
+1

लवली सामग्री, संदेह है कि आप इसे बेहतर कर सकते हैं। – JustBaron

2
मेरे लिए

इस पढ़ता है जैसे आप पूर्ण-स्ट्रिंग 4,6,8 निकालना चाहते हैं। यदि हां, तो secondid= के बाद this regex101 demo में भाग निकालने के लिए capturing group का उपयोग क्यों न करें।

preg_match('/\bsecondid=([\d,]+)/', $string, $out) 
  • \b निकालने के लिए
  • \d अंकों [0-9] के लिए

अपने updated code sample at eval.in देखें एक short है भाग के लिए एक word boundary

  • (कब्जा समूह) मेल खाता है। यदि आवश्यक हो, तो आप अभी भी return the exploded part कर सकते हैं।

  • +2

    आप एक घंटे पहले कहाँ थे: पी –

    +0

    धन्यवाद, यह भी काम करता है। – parik

    संबंधित मुद्दे