سؤال

Looking fo possibility to detect if $string is match all words in $array. Words order not known in advance (user typed text).

array(
  'test',
  'shmest',
  'zest',
  'fest',
  'etcest'
);

I undertand that i can:

$is_match = true;
foreach ($array as $word) {
  if (!strpos($string, $word) === false) {
    $is_match = false;
    break;
  }
}

(Can|Should) i make somethin like above via preg_match[_all]?

EDIT1

Priority is less memory and fast work.

Tested 2 unswers and own above https://eval.in/144266 so my is fastest

And $string can contain of any symbols

هل كانت مفيدة؟

المحلول

You can create a RegEx with LookAheads:

$regex='/(?=.*?'.implode(')(?=.*?', $needles).')/s';

then simple check against your string:

if (preg_match($regex,$string)===1) echo 'true';

Demo code: https://eval.in/144296
Explained RegEx: http://regex101.com/r/eQ0hU4

نصائح أخرى

Use preg_split() and array_intersect():

$words = preg_split("/(?<=\w)\b\s*/", $input, -1, PREG_SPLIT_NO_EMPTY);
echo (array_intersect($arr, $words) == $arr) ? 'True' : 'False';

Basically preg_split() splits your input string into an array of words. array_intersect() checks if all the elements in $arr are present in $words.

Demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top