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

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

本文介绍了检查字符串是否包含数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测一个字符串是否包含至少一个存储在数组中的URL.

I am trying to detect whether a string contains at least one URL that is stored in an array.

这是我的数组:

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

该字符串由用户输入并通过PHP提交.在确认页面上,我想检查输入的URL是否在数组中.

The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.

我尝试了以下操作:

$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
    echo "Match found";
    return true;
}
else
{
    echo "Match not found";
    return false;
}

无论输入什么,返回值始终为找不到匹配项".

No matter what is inputted the return is always "Match not found".

这是正确的做事方式吗?

Is this the correct way of doing things?

推荐答案

尝试一下.

$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
    //if (strstr($string, $url)) { // mine version
    if (strpos($string, $url) !== FALSE) { // Yoshi version
        echo "Match found";
        return true;
    }
}
echo "Not found!";
return false;

使用 stristr()或,如果您要检查不区分大小写的内容.

Use stristr() or stripos() if you want to check case-insensitive.

这篇关于检查字符串是否包含数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:09