检查字符串是否包含数组的所有值

First, let me explain what I will do with this piece of code. I have a database and a user interface to search the values within. Users are likely to type more than one keyword. So that I need to check if all the values in the array exist in my database.

For instance if they would type "green apple" and I had a string value of this kind "That greenish pineapple is gross", I am supposed the display this search result. On this account I figured out that somehow I need to find a way to check if the string values contain all values in the array, or not.

Thanks a million

I guess mysql full text search can help you if you get your array from database.

If you're not searching through TEXT, you can use MySQL Like.

CREATE TABLE TableA (
    `text` VARCHAR(255) NOT NULL PRIMARY KEY
);

INSERT INTO TableA (`text`) VALUES
('I like green and purple apples'),
('I hate red apples'),
('You like oranges');

You'll have to build the string of Likes from the array in PHP. Below I use PDO, but you can easily adjust it for mysqli.

$search_query = "green apples";
$keywords = explode(' ', $search_query);

$where = '1'; /* We use the 1 so we can prepend 'AND' w/o another case. */
foreach ($keywords as &$word) {
    $where .= " AND LIKE ?";
    $word = "%{$word}%";
}

unset($word);

$stmt = $PDO_Connection->prepare("SELECT `text` FROM Table A WHERE {$where}");
if ($stmt->execute([$keywords])){
    while ($row = $stmt->fetch()){
        echo $row['text'] . '<br />';
    }
}

If you are searching through text, you can do something similar with Full Text Search