简体   繁体   English

在PHP的句子中找到一个单词

[英]find a word in a sentence in php

I have this sentence: 我有这句话:

$newalt="My name is Marie";

I want to include a page if marie or josh is found: 如果找到玛丽或乔希,我想包含一个页面:

$words = array("marie", "josh");

$url_string = explode(" ", $newalt);

if(!in_array($url_string, $words)){
    echo "marie or josh are not in array";
}

the problem is, when I run this php it shows "marie or josh are not in array" and marie is the array (or should be). 问题是,当我运行此php时,它显示“ marie或josh不在数组中”,并且marie是数组(或应该是)。 What is wrong? 怎么了?

The solution using array_intersect and array_map functions: 使用该溶液array_intersectarray_map功能:

$newalt = "My name is Marie";
$words = ["marie", "josh"];

$url_string = explode(" ", $newalt);

if (empty(array_intersect($words, array_map("strtolower", $url_string)))) {
    echo "marie or josh are not in array";
}

http://php.net/manual/en/function.array-intersect.php http://php.net/manual/zh/function.array-intersect.php

您在数组中错误地使用了in_array()来检查第一个参数在第二个参数中。

in_array(strtolower($words[0]), array_map('strtolower', $url_string)) && in_array(strtolower($words[1]), array_map('strtolower', $url_string))

You have 2 errors. 您有2个错误。 First, in_array() is case-sensitive. 首先, in_array()区分大小写。 You need to make the haystack all lowercase first. 您需要先将干草堆全部小写。 Second, in_array() does not accept an array as the needle. 其次, in_array()不接受数组作为指针。 To overcome this, you can use something like array_diff() : 为了克服这个问题,您可以使用array_diff()类的东西:

$newalt="My name is Marie";
$words = array("marie", "josh");

$url_string = explode(" ", strtolower($newalt));

if(count(array_diff($words, $url_string) == count($words)){
    echo "marie or josh are not in array";
}

The first parameter of the in_array function is a array. in_array函数的第一个参数是数组。 Your $words array is filled with strings and not arrays. 您的$ words数组填充有字符串,而不是数组。

Maybe try something like this: 也许尝试这样的事情:

$words = array("marie", "josh");

$urlStrings = explode(" ", $newalt);

foreach ($urlStrings as $urlString) {
    if(!in_array($urlString, $words)){
        echo "marie or josh are not in array";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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