regex — PHP preg_match_all () соответствует всем словам, кроме предлога, прилагательные, как и другие менее важные слова в массиве

PHP preg_match_all () соответствует всем словам, кроме некоторых слов в массиве.

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
preg_match_all('/(?<match>\w{3,}+)/', $input, $matches, PREG_PATTERN_ORDER);
print_r($matches['match']);

Это дает все слова с нежелательными словами.

Array
(
[0] => Lorem
[1] => Ipsum
[2] => simply
[3] => dummy
[4] => text
[5] => the
[6] => printing
[7] => industry
)

Необходимо возвращать только важные слова, а не прилагательные или прилагательные предлога, как другие менее важные слова в массиве.

$ исключением = массив (‘и’, ‘the’, ‘текст’, ‘просто’);

Было бы лучше, если бы мы могли использовать одну функцию для этой цели.

1

Решение

Создайте регулярное выражение с отрицательным предвкушением, закрепленным на границе слова:

'~\b(?!(?:and|the|text|simply)\b)\w{3,}~'

Увидеть regex demo

подробности

  • \b — граница слова
  • (?!(?:and|the|text|simply)\b) — нет and, theи т. д. как целое слово допускается сразу справа от текущего местоположения
  • \w{3,} — 3 или более слова.

PHP демо:

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
if (preg_match_all('/\b(?!(?:' . implode('|', $except) . ')\b)\w{3,}/', $input, $matches)) {
print_r($matches[0]);
}

Выход:

Array
(
[0] => Lorem
[1] => Ipsum
[2] => dummy
[3] => printing
[4] => industry
)
3

Другие решения

Вы можете просто подать заявку array_diff к вашему результату и тому $except массив:

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
preg_match_all('/(?<match>\w{3,}+)/', $input, $matches, PREG_PATTERN_ORDER);
print_r(array_diff($matches['match'], $except));

Выход:

Array
(
[0] => Lorem
[1] => Ipsum
[3] => dummy
[6] => printing
[7] => industry
)

демо на 3v4l.org

Если вы хотите, чтобы результирующий массив индексировался от 0, используйте array_values на этом то есть

print_r(array_values(array_diff($matches['match'], $except)));

Выход:

Array
(
[0] => Lorem
[1] => Ipsum
[2] => dummy
[3] => printing
[4] => industry
)
2

Вы могли бы использовать array_diff () чтобы исключить слова, которые у вас есть в $except:

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
preg_match_all('/(?<match>\w{3,}+)/', $input, $matches, PREG_PATTERN_ORDER);
$filtered = array_diff($matches['match'],$except);

var_dump($filtered);

// Output:
array(5) {
[0]=>
string(5) "Lorem"[1]=>
string(5) "Ipsum"[3]=>
string(5) "dummy"[6]=>
string(8) "printing"[7]=>
string(8) "industry"}
2

Вот пример использования array_diff() с explode(),

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$inputArray = explode(' ', $input);
$except = array('and', 'the', 'text', 'simply');
$results = array_values(array_diff($inputArray, $except));

echo '<pre>';
print_r($results);
echo '</pre>';

Это выведет:

 Array
(
[0] => Lorem
[1] => Ipsum
[2] => is
[3] => dummy
[4] => of
[5] => printing
[6] => industry.
)
1
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector