简体   繁体   中英

PHP checking multiple words in a long one word string

using strpos, I can find one word in a string, but how can I find many words?

I know how to do it when the string contains words that are separated with space, but for example, if I have array('hi','how','are','you') and a string $string = 'hihowareyoudoingtoday?' How can I return the total amount found to match?

You can use preg_match_all that returns the number of matches:

$words = array('hi','how','are','you');

$nb = preg_match_all('~' . implode('|', $words) . '~', $string, $m);

print_r($m[0]);

echo "\n$nb";

preg_match_all is a function that searches all occurences of a pattern in a string. In the present example, the pattern is:

~hi|how|are|you~

the ~ is only a pattern delimiter.

| is a logical OR

Note that the search is performed form left to right character by character in the string and each alternatives are tested until one matches. So the first word that matches in a position is stored as a match result (into $m ). Understanding this mechanism is important. For example, if you have the string baobab and the pattern ~bao|baobab~ , the result will be only bao since it is the first tested alternative.

In other words, if you want to obtain the largest words first, you need to sort the array by size before.

Yes, you can use strpos() in this case:

Example:

$haystack = 'hihowareyoudoingtoday?';
$needles = array('hi','how','are','you');
$matches = 0;
foreach($needles as $needle) { // create a loop, foreach string
    if(strpos($haystack, $needle) !== false) { // use stripos and compare it in the parent string
        $matches++; // if it matches then increment.
    }
}

echo $matches; // 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM