skip to Main Content

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"]

2

Answers


  1. 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]);
        }
      }
    }
    
    Login or Signup to reply.
  2. 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 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search