Find and identify which elements from an array exist in a string - php

I have an array let's say it looks like this:
$arr=array('aa','bb','cc');
Now let's say I have a string that looks like any of these:
$str='bb';
$str='A_STRING_bb_WITH_SOME_TEXT';
$str='ASTRINGbbWITHSOMETEXT';
$str='A+STRING+bb+WITH+SOME+TEXT';
$str='A STRING bb WITH SOME TEXT';
I would like a function that gives me:
$r=find_which_one($arr,$str);
$r should be "bb" for all of those. What's the best way to do this?

Something like this:
function find_which_one($arr,$str){
foreach($arr AS $needle){
if (strpos($str, $needle)){
return true; //returns true on the first match
}
}
return false
}

$arr=array('aa','bb','cc');
$str='A_STRING_bb_WITH_SOME_TEXT aa';
function find_which_one(array $arr,$str) {
$r = preg_match(
'/((' . implode(')|(', $arr) .'))/',
$str,
$matches
);
return ($r !== false) ? $matches[0] : $r;
}
$r=find_which_one($arr,$str);
var_dump($r);
Returns false if not found, else the value from $arr that occurred first

This will return the correct key. If not found, it will return false.
function find_which_one($keys,$value) {
foreach($keys as $key) if (strpos($value, $key)) return $key;
return false;
}

Using array_filter it is straight forward:
$arr = array('aa','bb','cc');
$str = 'A+STRING+bb+WITH+SOME+TEXT';
print_r ( array_filter($arr, function($k) use($str) {
return strpos($str, $k) !== FALSE; }) );
Array
(
[1] => bb
)
Or else:
$str = 'ASTRINGbbWITHSOMETEXT';
print_r ( array_filter($arr, function($k) use($str) {
return strpos($str, $k) !== FALSE; }) );
Array
(
[1] => bb
)

Related

Remove if array contains string from another array

So the idea is to remove from one array a list of numbers of other array, but it's only removing the first one, any help to solve this will be appreciated.
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
function myFilter($string) {
$to_remove = array("593984076233","593998016010");
foreach($to_remove as $remove) {
return strpos($string, $remove) === false;
}
}
$newArray = array_filter($my_array, 'myFilter');
foreach ($newArray as $val){
echo $val.'<br>';
}
The problem is that your filter will always return from the first iteration of the loop.
This instead will return false if it finds the entry and at the end of the loop will return true (i.e. not found at all)...
function myFilter($string) {
$to_remove = array("593984076233","593998016010");
foreach($to_remove as $remove) {
if ( strpos($string, $remove) !== false )
return false;
}
return true;
}
Another method is to use preg_grep to search the array for the items you want to remove, then use array_diff to remove them.
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");
$to_remove = "/" . implode("|", $to_remove) . "/";
$match = preg_grep($to_remove, $my_array);
$filtered = array_diff($my_array, $match);
var_dump($filtered);
// Lucas,593999843424
https://3v4l.org/PZ4I6
You can also bunch it up to a one liner like this:
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");
$filtered = array_diff($my_array, preg_grep("/" . implode("|", $to_remove) . "/", $my_array));
var_dump($filtered);

check if string exists in array element

Is there any function that can do what strpos does, but on the elements of an array ? for example I have this array :
Array
(
[0] => a66,b30
[1] => b30
)
each element of the array can contain a set of strings, separated by commas.
Let's say i'm looking for b30.
I want that function to browse the array and return 0 and 1. can you help please ? the function has to do the oppsite of what this function does.
Try this (not tested) :
function arraySearch($array, $search) {
if(!is_array($array)) {
return 0;
}
if(is_array($search) || is_object($search)) {
return 0;
}
foreach($array as $k => $v) {
if(is_array($v) || is_object($v)) {
continue;
}
if(strpos($v, $search) !== false) {
return 1;
}
}
return 0;
}
You could also use preg_grep for this.
<?php
$a = array(
'j98',
'a66,b30',
'b30',
'something',
'a40'
);
print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );
https://eval.in/412598

How to check if a string inside of an array,contains a part of a string in php?

I have this code:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
But is not working because,in_array instruction check the array for the complete string "backup" , which doesnt exist.I need to check for a part of the string,for example,to return true because backup is a part of the "Hello_backup" and "Beautiful_backup" strings
EDIT: I take the advice and i have used stripos like this:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
but now i get an error: "stripos() expects parameter 1 to be string, array given in if(stripos($arr,$word) !== false){"
Use implode to basically concatenate the array values as a string, then use strpos to check for a string within a string.
The first argument you pass to implode is used to separate each value in the array.
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
In this case you need to use stripos(). Example:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
Without a function:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
Try with strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
output :- DaNuDaNu
Here is the one line solution for you.
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
You can use $returned_a with array as your answer..
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )
Use this method. It is little bit simple to use.
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
Look this working example
According to your question
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>

Make new array from specifed string?

I have this kind of simple array:
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
I want to make new array that i will only have elements thats starts with 1_
Example
$new=array('1_noname.jpg','1_ok.jpg','1_stack.jpg','1_predlog.jpg');
Something like array_pop but how?
See array_filter():
$new = array_filter(
$puctures,
function($a) {return substr($a, 0, 2) == '1_'; }
);
A simple loop will do.
foreach ($pictures as $picture) {
if (substr($picture, 0, 2) == "1_") {
$new[] = $picture;
}
}
Use array_filter() to get your array:
$new = array_filter($puctures, function($item)
{
//here strpos() may be a better option:
return preg_match('/^1_/', $item);
});
This examples uses array_push() & strpos()
$FirstPictures = array();
foreach( $pictures as $pic => $value ) {
if ( strpos( $value, '1_' ) !== 0 ) {
array_push( $FirstPictures, $pic );
}
}
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
$new=array();
foreach($puctures as $value)
{
if(strchr($value,'1'))
$new[]=$value;
}
echo "<pre>"; print_r($new);

Find with like condition in array

I am having following array and I want to use search and sort.Search and sort are like sorting which we do with MySQL "LIKE" condition but in array not in database.
Array
(
[4] => Varun Kumar
[14] => Jason Ince
)
Like on typing 'jas' record with Jason Ince must come out of it with keys and values and rest of the record respectively.
Do you mean something like:
foreach($yourArr as $key => $value) {
if (strpos($value, $yourString) !== false) {
//results here
}
}
You can use array_filter:
$filtered_array = array_filter($original_array, create_function($a, 'return stristr($a,"jas")!==false'));
OR, if you're using php 5.3+, syntax is:
$filtered_array = array_filter($original_array, function($a){ return stristr($a,"jas")!==false });
function arraySearch( $array, $search ) {
foreach ($array as $a ) {
if(strstr( $a, $search)){
echo $a;
}
}
return false;
}
arraySearch(array("php","mysql","search"),"my"); // will return mysql
You could also use this way:
function check($yourString)
{
foreach($yourArr as $key => $value) {
if (strpos($value, $yourString) !== false)
return strpos($value, $yourString);
}
}
So that you can check the condition if not false.

Categories