<?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);
- Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
- Array
(
[0] => Array
(
[before] => Here are
[mention] => @user:123
[after] => and @user:456 mentions
)
[1] => Array
(
[before] => Here are @user:123 and
[mention] => @user:456
[after] => mentions
)
)
preferences:
76.13 ms | 402 KiB | 62 Q