Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all letters not used in a string

Tags:

string

php

I want to be able to do something likes this:

$str="abc";
echo findNot($str); //will echo "defghijklomnopqrstuvwxyz"
$str2="happy birthday";
echo findNot($str2); //will echo "cfgjklmnoqsuvwxz"

Basically, it would find all letters not represented in the string and return them in an array or string.

I could do this easily with a foreach and arrays of characters, but I was wondering if anyone had a more elegant solution.

like image 923
diracdeltafunk Avatar asked Apr 30 '12 23:04

diracdeltafunk


3 Answers

Here's what I came up with.

function findNot($str){
    return array_diff(range('a','z'), array_unique(str_split(strtolower($str))));
}
like image 120
Rocket Hazmat Avatar answered Nov 09 '22 11:11

Rocket Hazmat


How about this

$str="abc";
var_dump(findNot($str));

function findNot($string)
{
    $letters = range('a', 'z');
    $presents = array_map(function($i) { return chr($i); }, array_keys(array_filter(count_chars($string))));

    return array_diff($letters, $presents);
}

PS: implode the result if you need a string of chars, not array

PPS: not sure if it is a "more elegant" solution :-)

PPPS: another solution I could think of is

$str="abc";
var_dump(findNot($str));

function findNot($string)
{
    $letters = range('a', 'z');
    $presents = str_split(count_chars($string, 4));
    return array_intersect($letters, $presents);
}
like image 4
zerkms Avatar answered Nov 09 '22 09:11

zerkms


You could do something like this:

$text = 'abcdefghijklmnop';
$search = array('a','b','c');

$result = str_replace($search, '', $text);
like image 3
erichert Avatar answered Nov 09 '22 10:11

erichert