2014-02-05 61 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