2014-02-05 60 views
0

我已經搜索了一個這樣的例子,但似乎無法找到它。preg_replace但@符號的所有內容

我期待取代一切的字符串,但@texthere

$輸入= this is @cool isn't it?

$輸出= @cool

我可以刪除@cool使用preg_replace("/@(\w+)/", "", $Input);但無法弄清楚如何做到相反

+1

匹配想要的字符串與'preg_match',然後只分配'$ output = $ extracted_string'。 –

回答

3

您可以匹配@\w+,然後替換原始字符串。或者,如果你需要使用preg_replace,你應該能夠與第一捕獲組來取代一切:

$output = preg_replace('/.*(@\w+).*/', '\1', $input); 

使用的preg_match解決方案(我假定這將有更好的表現):

$matches = array(); 
preg_match('/@\w+/', $input, $matches); 
$output = $matches[0]; 

兩種模式上面沒有解決如何處理多次匹配輸入的問題,例如this is @cool and @awesome, right?

+0

處理多個匹配輸入的最佳方法是什麼?我想這應該是'preg_match_all' – Jako

+1

只要使用'preg_match_all'並迭代結果,它會給你所有匹配的字符串。 – helion3

+0

感謝您的幫助,這幫助我找到了一個可行的解決方案。 – Jako