Jump to content

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


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!!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.