我已經搜索了一個這樣的例子,但似乎無法找到它。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'。 –