Jump to content

[SOLVED] compare two strings and return value of differences between them


cunoodle2

Recommended Posts

Can I compare two strings and return a value somehow that shows the difference between them.  Like this..

 

$a = "php freaks";

$b = "phe";

 

Some how then do $a - $b and return "fraks"

 

Im looking for basically letters that are in the first string that are NOT in the second one.

I don't know of a PHP function that can do that. Guess you'll have to do it the hard way. BTW, what happened to the space in between php and freaks? Did that get cutoff or something?

 

I definitely made a mistake there.  You are correct and the returned value should have been...

 

" fraks"

 

I figured I'd do it the hard way any way for fun but I know I'd save time if there was an existing php function for it.  If anyone else happens to have a solution for this let me know.

I don't know of anything like that, so here's what I would do.

 

$a = "php freaks";
$b = "phe";
$b = explode('',$b);
foreach ($b as $c) {
     $a = str_replace($c, '', $a);
}
echo $a;

 

I think that should work.

 

 

Edit - Or this:

$a = "php freaks";
$b = "phe";
$c = strlen($b);
for ($e = 0; $e < $c; $e++) {
     $a = str_replace($b[$e], '', $a);
}
echo $a;

I believe that works too.

That worked like a charm but I initially got a few warnings...

Warning: explode() [function.explode]: Empty delimiter in file.php on line 46

Warning: Invalid argument supplied for foreach()

 

I changed the code to this..

$b = str_split($b);
foreach ($b as $c) 
{
	$a = str_replace($c, '', $a);
}
echo $a;

 

It works PERFECT.  Thank you very much for the assistance!!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.