简体   繁体   中英

How to find a string in jumbled letters

I need to write a program to find a word in jumbled letters.For eg:Consider the string $example = "ahwerlyp"; I need to find the word help from the string.How can i Find it.Any help would be appreciated.

I have tried to use substr() function but it only return the string.if it is all in same line,otherwise it return zero

<?php
$example = "ahwerlyp";
$findword = "help";
/**how to find the word help from it**/


 if($findword is present in $example)
{
echo "exists";
}

?>
  1. Split each word into an array containing all the individual letters. (Can be done for example using preg_split('//u', 'word', -1, PREG_SPLIT_NO_EMPTY) )

  2. For each word, count how many times each letter occurs - array_count_values gives you an array with the input array values (our individual letters) as keys, and the count as value.

  3. Loop over the counted letters from the second word, and check if the count of the same letter in the first word is greater or equal at least. If that is not the case for any of the letters from the second word, it is not “contained” in the first one.

Let's wrap all that into a nice little function, and we get the following:

function does_a_contain_b($a, $b) {
  // split both words into individual letters, and count their occurrences
  $letters_given  = array_count_values(preg_split('//u', $a, -1, PREG_SPLIT_NO_EMPTY));
  $letters_needed = array_count_values(preg_split('//u', $b, -1, PREG_SPLIT_NO_EMPTY));

  // we assume b is going to be contained in a for now
  $contained = true;

  foreach($letters_needed as $letter => $count) {
    // if the letter from 2nd word does not occur in the 1st one at all,
    // or the count in 2nd is not at least equal to that of 1st,
    // we set our flag to false, and break out of the loop
    if(!isset($letters_given[$letter]) || $letters_given[$letter] < $count) {
      $contained = false;
      break;
    }
  }
  return $contained;
}

// a couple of test cases
var_dump(
  does_a_contain_b('ahwerlyp', 'help'),  // true
  does_a_contain_b('ahwerlyp', 'hhelp'), // false
  does_a_contain_b('ahwerlyp', 'hype'),  // true
  does_a_contain_b('ahwerlyp', 'foobar') // false
);

Please replace your code with this code:

<?php
$example = "ahwerlyp";
$findword = "help";

if (!array_diff(str_split($findword), str_split($example))) {
       echo "exists";
} else {
       echo "not exist";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM