检查字符串是否包含数组中的值 [英] Check if string contains a value in array

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

问题描述

我试图检测一个字符串是否至少包含一个存储在数组中的 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;
}

无论输入什么,返回的总是Match not found".

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()stripos() 如果你想检查不区分大小写.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆