php - matching substring in 2nd array -


php newbie, have 2 arrays, need loop through array1 , $value = 2, see if there $key match anywhere in $key of array (e.g. uit found in fruit1 , fruit 4) divide matching keys value 2.

i've been trying use preg_match, going odd along way , i'm not sure i'm going wrong. insights appreciated.

<?php $array = array( 'fruit1' => 1, 'hugo' => 2, 'helmet' => 3, 'fruit4' => 4, 'captain' => 5);  $array1 = array( 'uit' => 2, 'tes' => 1, 'ain' => 3,  );   foreach($array1 $key=>$value){  if($value==2){  $ch=$key;  $pattern = '/[$ch]/';  foreach($array $key=>$value){    if(preg_match($pattern, $key)){      $newvalue =$value[$key]/2;      echo "$key $newvalue";    }}}}?> 

assumption

so, basically, want check if each of $array1 keys substring of $array, right?

first problem (the pattern)

the regex pattern /[$ch]/ incorrect since means:

literally match single character present in following list ($, c, h)

this pattern match:

  • hugo
  • helmet
  • captain

corrected pattern

i think want along lines of $pattern = '/' . $ch . '/';.

in case var $ch gets expanded first element of $array1 becomes /uit/.

this pattern means:

literally match sequence uit

this pattern match:

  • fruit1
  • fruit4

preg_match not needed

you can use strpos.

foreach($array1 $needle => $val1){     if($val1 == 2) {         foreach ($array $haystack => $val2) {             if (strpos($haystack, $needle) !== false) {                 echo "$haystack => $val2\n";             }          }     } } 

see code @ php sandbox


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -