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

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

无论输入什么,返回值总是“未找到匹配”。

这是正确的做事方式吗?

215403 次浏览

Try this.

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

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

Try this:

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

- Thanks

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

output

bool(true)
$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';
}

You are checking whole string to the array values. So output is always false.

I use both array_filter and strpos in this case.

<?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";

If your $string is always consistent (ie. the domain name is always at the end of the string), you can use explode() with end(), and then use in_array() to check for a match (as pointed out by @Anand Solanki in their answer).

If not, you'd be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.

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

The expression above could probably be improved (I'm not particularly knowledgeable in this area)

Here's a demo

This was a lot easier to do if all you want to do is find a string in an array.

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

Here is a mini-function that search all values from an array in a given string. I use this in my site to check for visitor IP is in my permitted list on certain pages.

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
}

how to use

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

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

Simple str_replace with count parameter would work here:

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

More Info - https://www.techpurohit.in/extended-behaviour-explode-and-strreplace-php

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

I think that a faster way is to use 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";
}

I find this fast and simple without running loop.

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

Little explanation!

  1. Create new variable with $newStr replacing value in array of original string.

  2. Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.

  3. if it is vice versa of 2, i.e, while doing string comparison, both original and new string was not matched, that means, something got replaced, hence value in array exists in string.

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

this is the best approach search for any substring , case-insensitive and fast

just like like im mysql

ex:

select * from table where name = "%web%"

You can concatenate the array values with implode and a separator of | and then use preg_match to search for the value.

Here is the solution I came up with ...

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


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

I came up with this function which works for me, hope this will help somebody

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

Also, note that answers with strpos() will return true if the matching word is a part of other word. For example if word list contains 'st' and if your string contains 'street', strpos() will return true