I think this will do what you need. Please check out the demo for an explanation of everything that regex does, or post a comment if you have a question.
Regex:
((?:[\w,.\-?]+\h){0,5})\b' . . '\b((?:.+\h){2,5})
Demo: https://regex101.com/r/vG8qT2/1
PHP:
<?php $string = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed.'; $term = 'dolore magna'; $min = 0; $max = 5; preg_match('~((?:[\w,.\-?]+\h){'.$min.','.$max. '})\b' . preg_quote($term) . '\b((?:.+\h){'.$min.','.$max.'})~', $string, $matches); print_r($matches);
Demo: https://eval.in/410063
Please note that the resulting values will be in $matches[1] and $matches[2] .
chris85
source share