How to make if condition word found in array [duplicate] - php

This question already has answers here:
Search for partial string in PHP array? Search value contains hashtag
(4 answers)
Closed last year.
In PHP
echo $avatar["name"];
$array = ["hello", "world", "!"];
$string = "wor";
if (in_array($string, [$array])){
echo "match";
}else
echo "not match";
I want a script like that to print match if the word found in array , not string equal to array

You can try like this :
function partial_array_search( $array, $keyword ) {
$found = [];
// Loop through each item and check for a match.
foreach ( $array as $string ) {
// If found somewhere inside the string, add.
if ( strpos( $string, $keyword ) !== false ) {
$found[] = $string;
}
}
return $found;
}
$array = ["hello", "world", "!"];
$string = "wor";
$data = partial_array_search( $array, $string );
if($data){
print_r($data) ;
}else{
echo 'NOT MATCH';
}

Related

check a string contains any word from array

i have a set of predefined array contains strings and words.I am trying to check whether my string contains at least one word from that array.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
i tried many ways,but not correct solution
first method
$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";
second method
if (stripos(json_encode($array),$string) !== false) { echo "found";}
else{ echo "not found";}
I suppose you are looking for a match which is any of the words.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code|testy';
foreach ($array as $item ) {
if(preg_match("/\b{$string}\b/i", $item)) {
var_dump( $item );
}
}
You have to iterate over the array and test each one of the cases separately, first 'code', then 'testy', or whatever you want. If you json_encode, even if you trim both of strings to do this comparaison, the return will be not found.
But in the first string if you had like this
$array = array("PHP code testy Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array
you will get surely a "found" as return.
if (stripos(trim(json_encode($array)),trim($string)) !== false) { echo "found";}
else{ echo "not found";}
You could use explode() to get an array from the strings and then go through each of them.
$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';
foreach(explode(' ', $string) as $key => $value) {
foreach($array as $arrKey => $arrVal) {
foreach(explode(' ', $arrVal) as $key => $str) {
if ($value == $str) {
echo $str . ' is in array';
}
}
}
}

Search for matching partial values in an array [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
startsWith() and endsWith() functions in PHP
(34 answers)
Closed 1 year ago.
$target = 285
$array = array("260-315", "285-317", "240-320")
I need to search the array for the value that begins with the $target value. Also, the $target value will not be limited to 3 digits so I'm searching for a match of the digits before the hyphen.
So I want to end up with
$newTarget = 285-317
$finalTarget = 317
Note: I'm only searching for a match of the digits before the hyphen so "200-285" would not be a match
What you asked me in comment(below my answer),for that you can do it like below (My changed answer):-
<?php
$target = 285;
$array = array('260-315', '285-317', '240-320',"200-285");
foreach($array as $key=>$value){
if($target ==explode('-',$value)[0]){
echo $newTarget = $array[$key];
echo PHP_EOL;
echo $finalTarget = explode('-',$array[$key])[1];
}
}
?>
https://eval.in/702862
I can help you filter your array down to members that start with your target.
You can then split the return values to get to your final target.
<?php
$target = '285';
$array = array('260-315', '285-317', '240-320');
$out = array_filter($array, function($val) use ($target) {
return strpos($val, $target) === 0;
});
var_export($out);
Output:
array (
1 => '285-317',
)
<?php
$target = 285;
$arrStack = array(
"260-315",
"285-317",
"240-320",
);
$result = preg_grep('/'.$target.'/',$arrStack);
echo "<pre>"; print_r($result); echo "</pre>";
Something like this could work for you ? array_filter
$target = 285;
$array = array("260-315", "285-317", "240-320");
$newTarget = null;
$finalTarget = null;
$filteredArray = array_filter($array, function($val) use ($target) {
return strpos($val, $target."-") === 0;
});
if(isset($filteredArray[0])){
$newTarget = $filteredArray[0];
$finalTarget = explode($filteredArray[0], "-")[1];
}
Instead of finding what matches, you could exclude what doesn't match with array_filter.
For example:
$target = 285;
$original = array('260-315', '285-317', '240-320');
$final = array_filter($original, function ($value) use ($target) {
// Check if match starts at first character. Have to use absolute check
// because no match returns false
if (stripos($value, $target) === 0) {
return true;
}
return false;
});
The $final array will be a copy of the $original array without the non-matching values.
To output the first digits, you can then loop through your array of matches and get the value before the hyphen:
foreach ($final as $match) {
$parts = explode('-', $match);
if (is_array($parts) && ! empty($parts[0])) {
// Show or do something with value
echo $parts[0];
}
}
Use array_filter:
Example:
$target = '260';
$array = ['260-315', '285-317', '240-320'];
$matches = array_filter($array, function($var) use ($target) { return $target === explode('-', $var)[0]; });
print_r($matches);
Output:
Array
(
[0] => 260-315
)

PHP Check if array element exists in any part of the string

I know how to find if your string equals an array value:
$colors = array("blue","red","white");
$string = "white";
if (!in_array($string, $colors)) {
echo 'not found';
}
...but how do I find if the string CONTAINS any part of the array values?
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!in_array($string, $colors)) {
echo 'not found';
}
Or in one shot:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")",$string,$m)) {
echo "Found ".$m[0]."!";
}
This can also be expanded to only allow words that start with an item from your array:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))",$string,$m)) {
Or case-insensitive:
if( preg_match("(".implode("|",array_map("preg_quote",$colors)).")i",$string,$m)) {
CI with starting only:
if( preg_match("(\b(?:".implode("|",array_map("preg_quote",$colors))."))i",$string,$m)) {
Or anything really ;)
Just loop the array containing the values, and check if they are found in the input string, using strpos
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
foreach ( $colors as $c ) {
if ( strpos ( $string , $c ) !== FALSE ) {
echo "found";
}
}
You can wrap it in a function:
function findString($array, $string) {
foreach ( $array as $a ) {
if ( strpos ( $string , $a ) !== FALSE )
return true;
}
return false;
}
var_dump( findString ( $colors , "whitewash" ) ); // TRUE
Try this working solution
$colors = array("blue", "red", "white");
$string = "whitewash";
foreach ($colors as $color) {
$pos = strpos($string, $color);
if ($pos === false) {
echo "The string '$string' not having substring '$color'.<br>";
} else {
echo "The string '$string' having substring '$color'.<br>";
}
}
There is no built-in function for that, but you could do something like:
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
if (!preg_match('/\Q'.implode('\E|\Q',$colors).'\E/',$string)) {
echo 'not found';
}
This basically makes a regex from your array and matches the string against it. Good method, unless your array is really large.
You would have to iterate over each array element and individually check if it contains it (or a substr of it).
This is similar to what you want to do:
php check if string contains a value in array
$colors = array("blue","red","white");
$string = "whitewash"; // I want this to be found in the array
$hits = array();
foreach($colors as $color) {
if(strpos($string, $color) !== false) {
$hits[] = $color;
}
}
$hits will contain all $colors that have a match in $string.
if(empty($hits)) {
echo 'not found';
}

Check if string contains a value in array [duplicate]

This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
I am trying to detect whether a string contains at least one URL that is stored in an array.
Here is my array:
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
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.
I have tried the following:
$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?
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.
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";
}
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
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
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";
}
$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)
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
stripos function is not very strict. it's not case sensitive or it can match a part of a word
http://php.net/manual/ro/function.stripos.php
if you want that search to be case sensitive use strpos
http://php.net/manual/ro/function.strpos.php
for exact match use regex (preg_match), check this guy answer https://stackoverflow.com/a/25633879/4481831
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
}
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
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";
$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';
}
$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 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!
Create new variable with $newStr replacing value in array of original string.
Do string comparison - If value is 0, that means, strings are equal and nothing was replaced, hence no value in array exists in string.
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%"
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

Check if string contains word in array [duplicate]

This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $string contains any of the words in $bad?
So far I have:
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
// YES! }
}
Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
1) The simplest way:
if ( in_array( 'three', ['one', 'three', 'seven'] ))
...
2) Another way (while checking arrays towards another arrays):
$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string )
{
foreach ( $keywords as $keyword )
{
if ( strpos( $string, $keyword ) !== FALSE )
{ echo "The word appeared !!" }
}
}
can you please try this instead of your code
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
$place = strpos($string, $bad);
if (!empty($place)) {
echo 'Bad word';
exit;
} else {
echo "Good";
}
}
There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:
$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
echo 'Bad words found';
} else {
echo 'No bad words in the string';
}
The single line:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
does all the work.
You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,
//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
function containsBadWord($str){
//get rid of extra white spaces at the end and beginning of the string
$str= trim($str);
//replace multiple white spaces next to each other with single space.
//So we don't have problem when we use explode on the string(we dont want empty elements in the array)
$str= preg_replace('/\s+/', ' ', $str);
$word_list= explode(" ", $str);
foreach($word_list as $word){
if( isset($GLOBALS['bad_words'][$word]) ){
return true;
}
}
return false;
}
$string = "This dude is a mothertrucker";
if ( !containsBadWord($string) ){
//doesn't contain bad word
}
else{
//contains bad word
}
In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.
Put and exit or die once it find any bad words, like this
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
echo YES;
die(); or exit;
}
}
You can do the filter this way also
$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.
{
echo "There is a bad word in the string";
}
else {
echo "There is no bad word in the string";
}
Wanted this?
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot', 'mothertrucker');
foreach ($bads as $bad) {
if (strstr($string,$bad) !== false) {
echo 'NO<br>';
}
else {
echo 'YES<br>';
}
}
If you want to do with array_intersect(), then use below code :
function checkString(array $arr, $str) {
$str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase
$matchedString = array_intersect( explode(' ', $str), $arr);
if ( count($matchedString) > 0 ) {
return true;
}
return false;
}
I would go that way if chat string is not that long.
$badwords = array('mothertrucker', 'ash', 'whole');
$chatstr = 'This dude is a mothertrucker';
$chatstrArr = explode(' ',$chatstr);
$badwordfound = false;
foreach ($chatstrArr as $k => $v) {
if (in_array($v,$badwords)) {$badwordfound = true; break;}
foreach($badwords as $kb => $vb) {
if (strstr($v, $kb)) $badwordfound = true;
break;
}
}
if ($badwordfound) { echo 'You\'re nasty!';}
else echo 'GoodGuy!';
$string = "This dude is a good man";
$bad = array('truck','shot','etc');
$flag='0';
foreach($bad as $word){
if(in_array($word,$string))
{
$flag=1;
}
}
if($flag==1)
echo "Exist";
else
echo "Not Exist";

Categories