Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to remove the letters from word1 if they do not exist in word2 with PHP

3 Answers

0 votes
function remove_non_common_letters($word1, $word2) {
    $result = '';
    $chars = str_split($word1);
    
    foreach ($chars as $char) {
        if (strpos($word2, $char) !== false) {
            $result .= $char;
        }
    }
    
    return $result;
}

$word1 = "forest";
$word2 = "tor";

$result = remove_non_common_letters($word1, $word2);

echo $result;



/*
run:

ort

*/

 



answered Jul 10, 2025 by avibootz
0 votes
function remove_non_common_letters($word1, $word2) {
    $word1Array = str_split($word1);
    $word2Array = str_split($word2);
    
    $filtered = array_filter($word1Array, function($char) use ($word2Array) {
        return in_array($char, $word2Array);
    });
    
    return implode('', $filtered);
}

$word1 = "forest";
$word2 = "tor";

$result = remove_non_common_letters($word1, $word2);

echo $result;



/*
run:

ort

*/

 



answered Jul 10, 2025 by avibootz
0 votes
function remove_non_common_letters($word1, $word2) {
    $word2Flipped = array_flip(str_split($word2));
    
    $result = '';
    foreach (str_split($word1) as $char) {
        if (isset($word2Flipped[$char])) {
            $result .= $char;
        }
    }
    
    return $result;
}

$word1 = "forest";
$word2 = "tor";

$result = remove_non_common_letters($word1, $word2);

echo $result;



/*
run:

ort

*/

 



answered Jul 10, 2025 by avibootz
...