我已经搜索了一个这样的例子,但似乎无法找到它。preg_replace但@符号的所有内容
我期待取代一切的字符串,但@texthere
$输入= this is @cool isn't it?
$输出= @cool
我可以删除@cool
使用preg_replace("/@(\w+)/", "", $Input);
但无法弄清楚如何做到相反
我已经搜索了一个这样的例子,但似乎无法找到它。preg_replace但@符号的所有内容
我期待取代一切的字符串,但@texthere
$输入= this is @cool isn't it?
$输出= @cool
我可以删除@cool
使用preg_replace("/@(\w+)/", "", $Input);
但无法弄清楚如何做到相反
您可以匹配@\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?
匹配想要的字符串与'preg_match',然后只分配'$ output = $ extracted_string'。 –