2013-06-18 215 views
0

有誰知道什麼是正則表達式得到以下結果:正則表達式提取字符串

Hello world, Another day to die. => Hello world 

我想下面的表達式:

/^.*,/ 

但結果是「你好世界!'

我想忽略最後一個字符(!)。任何人都可以幫我一把嗎?

此致敬禮。

+2

我沒有看到任何'!'。 – Toto

回答

2

使用正前瞻:

/^.*?(?=,)/ 

使用例:

preg_match('/^.*?(?=,)/', "Hello world, Another day to die.", $matches); 
echo "Found: {$matches[0]}\n"; 

輸出:

Found: Hello world 
+0

它的工作原理,謝謝! –

0

隨着@ acdcjunior的答案,這裏有幾個選擇:

"/^.*?(?=,)/" // (full match) 
"/^(.*?),/" // (get element 1 from result array) 
"/^[^,]+/" // (full match, bonus points for matching full string if there is no comma) 
explode(",",$input)[0] // PHP 5.4 or newer 
array_shift(explode(",",$input)) // PHP 5.3 and older 
substr($input,0,strpos($input,",")) 

有很多方法可以實現這一點;)

0

這又是一個,

$str = 'Hello world, Another day to die'; 
preg_match('/[^,]+/', $str, $match); 
0

使用以下命令:

/^[\w\s]+/ 
0

使用此,只有檢查字母:

/^[a-z]+ [a-z]+/i 

或無正則表達式:

$res = split(",", $string, 2)[0];