PHP的检查,如果字符串包含数组中的值 [英] php check if string contains a value in array

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

问题描述

我试图来检测一个字符串是否包含存储在一个阵列至少1个网址。

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

下面是我的数组:

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

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

The string is user entered 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()或的 stripos函数()如果你想检查不区分大小写。

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

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

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