Home > Software engineering >  How to search for word in array of slugs
How to search for word in array of slugs

Time:01-06

I have an array of locations slugs and a sentence that might have one of the locations. So I want to get the location in the sentence from the locations array

    $areas = 'garki-i,garki-ii,yaba,wuse-i,asokoro,maitama,jabi,jahi,dutse,gwarinpa,central-business-district,kubwa,lugbe,kaura,gudu,banana-island,new-karu,old-karu,kugbo,eko-atlantic,nyanya,mararaba,madalla,kuje,wuse-ii,utako,oulfa,kimunyu,ibara,cfc,joska,kabati,juja';
    $a_arr = explode(',', $areas);
    
    $tweet = "I live in Eko Atlantic and Yaba and I also work at Banana Island";
    $t_arr = explode(" ", strtolower($tweet));
    $location = [];
    
    for ($i = 0; $i < count($t_arr); $i  ) {
      for ($j = 0; $j < count($a_arr); $j  ) {
        if ($t_arr[$i] == $a_arr[$j]) {
          array_push($location, $a_arr[$j]);
        }
      }
    }
    
    $output = ["eko-atlantic", "yaba", "banana-island"];

I am getting ['yaba'] but I want ["eko-atlantic", "yaba", "banana-island"]

CodePudding user response:

You will need to change the inner loop such that it compares the complete string in $t arr[$i] to the entire string in $a arr[$j], rather than just comparing individual characters, in order to alter your code so that it correctly extracts the locations from the tweet. To accomplish this, compare the strings using the strcmp function:

for ($i = 0; $i < count($t_arr); $i  ) {
  for ($j = 0; $j < count($a_arr); $j  ) {
    if (strcmp($t_arr[$i], $a_arr[$j]) == 0) {
      array_push($location, $a_arr[$j]);
    }
  }
}

CodePudding user response:

Here is my solution

<?php 

$areas = 'garki-i,garki-ii,yaba,wuse-i,asokoro,maitama,jabi,jahi,dutse,gwarinpa,central-business-district,kubwa,lugbe,kaura,gudu,banana-island,new-karu,old-karu,kugbo,eko-atlantic,nyanya,mararaba,madalla,kuje,wuse-ii,utako,oulfa,kimunyu,ibara,cfc,joska,kabati,juja';
$a_arr = explode(',', $areas);

$tweet = "I live in Eko Atlantic and Yaba and I also work at Banana Island";
$t_arr = explode(" ", strtolower($tweet));
$location = [];

if ( $t_arr != null ) {
  
  foreach ($a_arr as $key => $value) {

    if ( preg_match ( '/'.str_replace('-', ' ', $value).'/', strtolower($tweet)) ) {
        array_push($location, $value);
    }
  }
}

var_dump( $location );
  • Related