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


82

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

这是我的数组:

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

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

我尝试了以下方法:

$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;
}

无论输入什么,返回值始终为“找不到匹配项”。

这是正确的做事方式吗?


查看我的答案,我认为您会发现它很有用。
FarrisFahad

Answers:


88

试试这个。

$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()


3
几乎-这将回显“未找到匹配项”,并且如果列表中的第一个URL不匹配(即使另一个URL匹配),则返回false。该else块的内容需要进入foreach循环以下。
Ulrich Schmidt-Goertz

感谢您发现这一点。刚刚改善了我的答案。
Daniele Vrut

您还错过了$ string之后的“)” :)
danyo

7
来自手册:**Note**: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
Yoshi

5
@danyo如果用户输入的域名,则此方法将无效site3.com。它将匹配mysite3.com时,它不应该
billyonecan

22

试试这个:

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

$string = 'my domain name is website3.com';

$url_string = end(explode(' ', $string));

if (in_array($url_string,$owned_urls)){
    echo "Match found"; 
    return true;
} else {
    echo "Match not found";
    return false;
}

- 谢谢


8
这假定字符串之间用空格分隔。例如,它会为以下字符串不工作My url is https://website3.com
ЕлинЙ.

4
甚至不适用于“我拥有website3.com域”。这是假定该字符串是在最后,您可以与用户提交的文本时不
塞缪尔·维瑟

20

str_replace使用count参数简单可以在这里工作:

$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
  echo "One of Array value is present in the string.";
}

更多信息-https: //www.techpurohit.com/extended-behaviour-explode-and-strreplace-php


很好,我有一个疑问..这对于匹配字符串的URL可以正常工作...我有一个字符串$ string ='you-are-nice'; $ string2 ='你是尼克尔'; 和我的$ match ='nice'; 我需要匹配单词nice,即使我的匹配字符串很好,也不要匹配它……
Srinivas08

15

如果您要做的就是在数组中找到一个字符串,那么这样做会容易得多。

$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}

1
您的输入数组实际上是一个字符串。
Burgi

3
我认为这是最佳答案,但由于代码中的简单错误,因此没有收到赞誉。@ Burgi我编辑了答案,现在它是数组,甚至更多,多个子数组,他的方法仍然运行良好!
塔里克

这很好用,但是它不会告诉您数组与哪个键匹配。
ahinkle

8
$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');

$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0; 
var_dump($result );

输出

bool(true)

2
以供参考; create_function在PHP 7.2中已弃用
Darryl E. Clarke

6

我认为更快的方法是使用preg_match

$user_input = 'Something website2.com or other';
$owned_urls_array = array('website1.com', 'website2.com', 'website3.com');

if ( preg_match('('.implode('|',$owned_urls_array).')', $user_input)){
    echo "Match found"; 
}else{
    echo "Match not found";
}

4
感谢您提供此代码段,它可能会提供一些有限的即时帮助。通过说明为什么这是一个很好的解决方案,正确的解释将极大地提高其长期价值,对于其他有类似问题的读者来说,这将是更加有用的。请编辑您的答案以添加一些解释,包括您所做的假设。参考
Alper t。Turker

我认为这是更好的答案
dryobs

为了更安全,点必须以以下方式逸出:addcslashes(implode('|', $owned_urls_array, '.'))
dryobs

更少的代码,但绝对比strpos慢得多
hndcrftd

4

这是一个微型函数,可以从给定字符串中的数组中搜索所有值。我在自己的网站上使用它来检查访问者IP是否在某些页面的允许列表中。

function array_in_string($str, array $arr) {
    foreach($arr as $arr_value) { //start looping the array
        if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
    }
    return false; //else return false
}

如何使用

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

//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
    echo "first: Match found<br>"; 
}
else {
    echo "first: Match not found<br>";
}

//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
    echo "second: Match found<br>"; 
}
else {
    echo "second: Match not found<br>";
}

演示:http : //phpfiddle.org/lite/code/qf7j-8m09


1
它区分大小写,对于不区分大小写的版本使用stripos
hndcrftd

3

如果您$string始终保持一致(即域名始终位于字符串的末尾),则可以explode()与配合使用end(),然后使用in_array()来检查匹配项(如@Anand Solanki在其答案中指出的)。

如果不是这样,最好使用正则表达式从字符串中提取域,然后再使用它in_array()来检查匹配项。

$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);

if (empty($matches[1])) {
  // no domain name was found in $string
} else {
  if (in_array($matches[1], $owned_urls)) {
    // exact match found
  } else {
    // exact match not found
  }
}

上面的表达方式可能会有所改善(我在这方面不是特别有知识)

这是一个演示


2

您可以使用爆破和|的分隔符来连接数组值。然后使用preg_match搜索值。

这是我想出的解决方案...

$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);

if(!preg_match("/$emails/i", $email)){
 // do something
}

应该是优雅的打勾答案
ceyquem,

1
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

1

您正在检查整个字符串是否为数组值。所以输出总是false

我同时使用array_filter,并strpos在这种情况下。

<?php
$urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$check = array_filter($urls, function($url){
    global $string;
    if(strpos($string, $url))
        return true;
});
echo $check?"found":"not found";

0

您没有正确使用函数in_array(http://php.net/manual/en/function.in-array.php):

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

$ needle必须在数组中具有一个值,因此您首先需要从字符串中提取url(例如,使用正则表达式)。像这样:

$url = extrctUrl('my domain name is website3.com');
//$url will be 'website3.com'
in_array($url, $owned_urls)

0

如果您试图获得完全匹配的单词(网址中没有路径)

$string = 'my domain name is website3.com';
$words = explode(' ', $string); 
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
var_dump(array_intersect($words, $owned_urls));

输出:

array(1) { [4]=> string(12) "website3.com" }

0
    $message = "This is test message that contain filter world test3";

    $filterWords = array('test1', 'test2', 'test3');

    $messageAfterFilter =  str_replace($filterWords, '',$message);

    if( strlen($messageAfterFilter) != strlen($message) )
        echo 'message is filtered';
    else
        echo 'not filtered';

0

我发现此过程既快速又简单,无需运行循环。

$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";

$newStr = str_replace($array, "", $string);

if(strcmp($string, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

$newStr = str_replace($array, "", $string2);

if(strcmp($string2, $newStr) == 0) {
    echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
    echo 'Word Exists - Some Word from array got replaced!';
}

一点解释!

  1. $newStr替换原始字符串数组中的值创建新变量。

  2. 做字符串比较-如果value为0,则意味着字符串相等,并且没有替换任何内容,因此string中数组中没有值。

  3. 如果是2,反之亦然,也就是说,在进行字符串比较时,原始字符串和新字符串均不匹配,这意味着替换了某些内容,因此字符串中存在数组中的值。


0
  $search = "web"
    $owned_urls = array('website1.com', 'website2.com', 'website3.com');
          foreach ($owned_urls as $key => $value) {
         if (stristr($value, $search) == '') {
        //not fount
        }else{
      //found
       }

这是搜索任何不区分大小写且快速的子字符串的最佳方法

就像我的mysql一样

例如:

从表中选择*,其中name =“%web%”


0

我想出了一个对我有用的功能,希望对您有所帮助

$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';

function checkStringAgainstList($str, $word_list)
{
  $word_list = explode(', ', $word_list);
  $str = explode(' ', $str);

  foreach ($str as $word):
    if (in_array(strtolower($word), $word_list)) {
        return TRUE;
    }
  endforeach;

  return false;
}

另外,请注意,如果匹配的单词是其他单词的一部分,则strpos()的答案将返回true。例如,如果单词列表包含“ st”,并且字符串包含“ street”,则strpos()将返回true


-3

谢谢您-能够使用原始问题的答案来开发易于使用的404错误页面检查器,以用于自定义404错误页面。

开始:

您需要通过array / DB等在站点中创建一个livePages数组,即使您的<dir>树列表也会通过修改来做到这一点:

使用原始的IDEA,但使用相似的文本而不是strpos,这使您可以搜索LIKE名称,因此也可以使用TYPOS,因此您可以避免或找到类似Sound-a和Look-a的名称...

<?php
// We need to GRAB the URL called via the browser ::
$requiredPage = str_replace ('/', '',$_SERVER[REQUEST_URI]);

// We need to KNOW what pages are LIVE within the website ::
$livePages = array_keys ($PageTEXT_2col );

foreach ($livePages as $url) {

if (similar_text($requiredPage,  $url, $percent)) {
    $percent = round($percent,2); // need to avoid to many decimal places ::
    //   if (strpos($string, $url) !== FALSE) { // Yoshi version
    if (round($percent,0) >= 60) { // set your percentage of "LIKENESS" higher the refiner the search in your array ::
        echo "Best Match found = " . $requiredPage . " > ,<a href='http://" . $_SERVER['SERVER_NAME'] . "/" . $url . "'>" . $url . "</a> > " . $percent . "%"; 
        return true;
    } 
}
}    
echo "Sorry Not found = " . $requiredPage; 
return false;
?>

希望这对某人有所帮助,例如本文帮助我在404ErrorDoc页面上创建了一个非常简单的搜索/匹配项。

该页面的设计将使服务器能够通过浏览器向任何被调用的URL提出可能的URL匹配...

它行之有效-而且太简单了,也许有更好的方法可以做到这一点,但是这种方法行得通。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.