How to find out if a substring exists in a string using PHP?

I know a lot of questions that have already been asked about this problem, but I could not find the right answer for my specific problem.

I have a search bar - "1 | 1"

I have an array containing the following values: "a" => "1 | 1", "b" => "2 | 1,1 | 1", "c" => "3 | 2,2 | 1"

All I want to do is just find if the search string exists in the array, it should return the key of the array. If several elements of the array have a search string, they should return all of them.

In this example, I expect to get "a" and "b", but when I use it strpos(), it gives me only "a".

How can I solve this problem?

Change **

This is my code.

function array_search_i($str, $array)
{
    $returnArray = array();
    foreach ($array as $key => $value) {
        if (strpos($str, $value) !== false) {
            array_push($returnArray, $key);
        }
    }
    return $returnArray;
}
+3
8

!==. .

$searchArray = array('2|2','1|1,3|3','1|1');
$search = '1|1';
foreach ($searchArray as $k=> $value) {
    if (strpos($value,$search) !== false) {
        $keysWithMatches[] = $k;
    }
}

print_r($keysWithMatches);
+2

preg_grep.

print_r(preg_grep("/1\|1/", $array));
+2
$keys = array();
foreach($a as $k=>$v){
    if(strpos($v,'1|1') !== false) $keys[] = $k;
}
+1

strpos " ".

array_keys. , , . , " ", , , , , array_map array_filter.

0

, , - PHP array_key().

:

$array = array("a" => "1|1", "b" => "2|1,1|1", "c" => "3|2,2|1");

$result = array_keys($array,'1|1');

print_r($result);
// 'a' => '1|1'

UPDATE:

print_r($array[$result[0]]); // Makes more sense.
                             // '1|1'
0

:

<?php
    $array = Array("a" => "1|1", "b" => "2|1,1|1","c" => "3|1,2|1","d" => Array("a1" => "1|1"));
    array_walk($array,"find");

    function find($value, $key) {
        if (!is_array($value)) {
            if (preg_match("/\b1\|1\b/i",$value)) {
            echo $key .'<br />';
            }
        }
        else {
            array_walk($value,"find");
        }
    }
?>

:

a
b
a1
0

array_filter() - , . .

$array = array("a"=>array("1|1"), "b"=>array("2|1","1|1"), "c"=>array("1|2"));
var_dump(array_keys(array_filter($array, function ($elem) { return in_array('1|1', $elem); } )));

OUTPUT

array(2) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
}
0

You can use array_keys with the search_value parameter to search for all values ​​in the array.

In this example, the keys of all matching exact values ​​will be obtained:

<?php
$searchArray = array('2|2','1|1','1|1');
$search = '1|1';
print_r(array_keys($searchArray, $search));
?>

(OR)

In this example, the key of all partial values ​​will be obtained

<?php
foreach($array as $key => $val) {
   if(strpos($val,'green') !== false) {
      $resKeys[] = $key;
   }
}

print_r($resKeys);
?>
0
source

All Articles