3v4l.org

run code in 300+ PHP versions simultaneously
<?php $text = 'Here are @user:123 and @user:456 mentions'; $contextSize = 5; $pattern = '~ @user:[0-9]+ \s* (*:mention) | \S+ \s* ~x'; $results = []; if (preg_match_all($pattern, $text, $matches)) { foreach ($matches['MARK'] as $k => $v) { $beforeIndex = max(0, $k - $contextSize); $beforeSize = $k - $beforeIndex; $afterIndex = $k + 1; $results[] = [ 'before' => join(array_slice($matches[0], $beforeIndex, $beforeSize)), 'mention' => $matches[0][$k], 'after' => join(array_slice($matches[0], $afterIndex, $contextSize)) ]; } } print_r($results);

preferences:
30.3 ms | 408 KiB | 5 Q