2013-05-15 30 views
0

我需要提取用逗號或逗號和空格分隔的字符串。 例子:如何提取用逗號分隔的字符串?

<?php 
    //regexp 
    $regexp = "/(select\s+(?<name>[a-z0-9]+)\s+(?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$)))/"; 
    //text 
    $text = "select this string1,string_2,string_3 ,string_4, string5,string_6"; 
    //prepare 
    $match = array(); 
    preg_match($regexp , $text , $match); 
    //print 
    var_dump($match); 
?> 

我創造了這個正則表達式:

(?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$)) 

但是,這並不正常工作。

謝謝!

+0

爆炸()或str_getcsv(),然後array_walk所得陣列的回調'trim' –

+0

'爆炸( '',$文本) '? –

回答

1

我建議你使用類似~(?|select ([^\W_]+) | *([^\W,]+) *,?),如果你想檢查你只獲得字母數字字符。例如:

$subject = 'select this string1,string_2,string_3 ,string_4, string5,string_6'; 
$pattern = '~(?|select ([a-z][^\W_]*+) | *+([a-z][^\W,_]*+) *+,?)~i'; 

preg_match_all($pattern, $subject, $matches); 

if (isset($matches[1])) { 
    $name = array_shift($matches[1]); 
    $strings = $matches[1]; 
} 

或者另一種方式:

$pattern = '~select \K[a-z][^\W_]*+| *+\K[a-z][^\W,]*+(?= *,?)~'; 
preg_match_all($pattern, $subject, $matches); 

if (isset($matches[0])) { 
    $name = array_shift($matches[0]); 
    $strings = $matches[0]; 
} 
4

我會用preg_split此:

$text = "select this string1,string_2,string_3 ,string_4, string5,string_6"; 
$stringArray = preg_split("/,\s*/",$text); 

但是這將是每個逗號後剛剛拆分容易得多,然後修剪結果:

$stringArray = explode(",",$text); 
+0

這不起作用,我需要字符串與「a-z0-9_」,沒有「·$%&/(/&%$·xxfr \ x45」:( 謝謝! –

+1

@OlafErlandsen你可以先爆炸,比你處理字符串 – Ibu