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';
}
}
}
}
Related
Hi I'm trying to check if a list of words (or any one of them) exists in a string. I tried some of the examples i found here, but i still can't get it to work correctly.
Any ideas what I'm doing wrong?
$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
if (in_array($ss3, $words) )
{
echo "found it";
}
Loop over your array, check for each element if it exists in the string
$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
foreach($words as $w){
if (stristr($ss3,$w)!==false)
echo "found $w \n";
}
Fiddle
You need to explode() your $ss3 string and then compare each item with your $words with loop
manual for in_array - http://php.net/manual/en/function.in-array.php
manual for explode() - http://php.net/manual/ru/function.explode.php
$matches = array();
$items = explode(" ",$ss3);
foreach($items as $item){
if(in_array($item, $words)){
$matches[] = $item; // Match found, storing in array
}
}
var_dump($matches); // To see all matches
This is how you will check for existence of a word from a string. Also remember that you must first convert the string to lowercase and then explode it.
$ss3="How to make a book";
$ss3 = strtolower($ss3);
$ss3 = explode(" ", $ss3);
$words = array ("book","paper","page","sheet");
if (in_array($ss3, $words) )
{
echo "found it";
}
Cheers!
You could use regular expressions. It would look something like this:
$ss3 = "How to make a book";
if (preg_match('/book/',$ss3))
echo 'found!!';
in_array will only check the complete string value in an array.
Now you can try this:
$string = 'How to make a book';
$words = array("book","paper","page","sheet");
foreach ($words as $val) {
if (strpos($string, $val) !== FALSE) {
echo "Match found";
return true;
}
}
echo "Not found!";
You can use str_word_count along with array_intersect like as
$ss3="How to make a book";
$words = array ("book","paper","page","sheet");
$new_str_array = str_word_count($ss3,1);
$founded_words = array_intersect($words,$new_str_array);
if(count($founded_words) > 0){
echo "Founded : ". implode(',',$founded_words);
}else{
echo "Founded Nothing";
}
Demo
This code will help you for better answer
<?php
$str="Hello World Good";
$word=array("Hello","Good");
$strArray=explode(" ",$str);
foreach($strArray as $val){
if(in_array($val,$word)){
echo $val."<br>";
}
}
?>
So here is situation let's imagine a string and an array:
$str = 'Sample string';
$arr = array('sample', 'string')
What would be the best way to determine if the given string has all of the words contained in the array? String can be longer, and has additional words, it does not matter. The only thing I need, is a function that given a string and an array would return true, if string contains every single word that is in array (case and order I'm which they appear does not matter)
You can simply use str_word_count with extra parameter 1 like as
$str = 'Sample string';
$arr = array('sample', 'string');
$new_arr = array_intersect(array_map('strtolower',str_word_count($str,1)),$arr);
print_r($new_arr);
Output:
Array
(
[0] => sample
[1] => string
)
Demo
Try this one:
<?php
$words = array('sample', 'string');
$str = 'sample string';
strtolower($str);
$strArr = explode(' ',$str);
$wordfound = false;
foreach ($strArr as $k => $v) {
if (in_array($v,$words)) {$wordfound = true; break;}
foreach($words as $kb => $vb) {
if (strstr($v, $kb)) $wordfound = true;
break;
}
}
if ($wordfound) {
echo 'Found!';
}
else echo 'Not found!';
If performance matters, I would use an associative array:
$words = array_flip(preg_split('/\\s+/', strtolower($str)));
$result = true;
foreach ($arr as $find) {
if (!isset($words[$find])) {
$result = false;
break;
}
}
Demo
Try this out.
$strArray = explode(" ", $str);
$result = array_intersect($strArray, $arr);
if(sizeof($result) == sizeof($arr)){
return TRUE;
}else{
return FALSE;
}
if this don't work, then try swapping the inputs in array_intersect($arr, $strArray)
You can add other functions to make all lowercase before comparing to give it a finishing touch.
$str = 'Sample string';
$str1=strtolower($str);
$arr = array(
'sample',
'string'
);
foreach($arr as $val)
{
if(strpos($str1,strtolower($val)) !== false)
{
$msg='true';
}
else
{
$msg='false';
break;
}
}
echo $msg;
I have a string that looks like this "thing aaaa" and I'm using explode() to split the string into an array containing all the words that are separated by space. I execute something like this explode (" ", $string) .
I'm not sure why but the result is : ["thing","","","","aaaa"]; Does anyone have an idea why I get the three empty arrays in there ?
EDIT : This is the function that I'm using that in :
public function query_databases() {
$arguments_count = func_num_args();
$status = [];
$results = [];
$split =[];
if ($arguments_count > 0) {
$arguments = func_get_args();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arguments));
foreach ($iterator as $key => $value) {
array_push($results, trim($value));
}
unset($value);
$filtered = $this->array_unique_values($results, "String");
foreach ($filtered as $key => $string) {
if (preg_match('/\s/',$string)) {
array_push($split, preg_split("/\s/", $string));
} else {
array_push($split, $string);
}
}
unset($string);
echo "Terms : ".json_encode($split)."<br>";
foreach ($filtered as $database) {
echo "Terms : ".json_encode()."<br>";
$_action = $this->get_database($database);
echo "Action : ".json_encode($_action)."<br>";
}
unset($database);
} else {
return "[ Databases | Query Databases [ Missing Arguments ] ]";
}
}
It might be something else that messes up the result ?!
If you are looking to create an array by spaces, you might want to consider preg_split:
preg_split("/\s+/","thing aaaa");
which gives you array ("thing","aaaa");
Taken from here.
try this:
$str = str_replace(" ", ",", $string);
explode(",",$str);
This way you can see if it is just the whitespace giving you the problem if you output 4 commas, it's because you have 4 whitespaces.
As #Barmar said, my trim() just removes all the space before and after the words, so that is why I had more values in the array than I should have had.
I found that this little snippet : preg_replace( '/\s+/', ' ', $value ) ; replacing my trim() would fix it :)
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";
I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}