Jump to content

compare chars in a string


xiaix

Recommended Posts

Best method to for the following?

// The following $str1 and $str2 should say they are identical
$str1 = "abcDEF";
$str2 = "EcFabD";

// The following $str1 and $str2 should say they are NOT identical because of the "a" "A" case difference.
$str1 = "abcDEF";
$str2 = "EcFAbD";

 

I'm comparing bitvector strings.  "ABC" is different than "abc".  "abc" is the same as "cba".

 

What's the best php function or method I should use?

 

Thank you.

 

 

Link to comment
Share on other sites

Try to google 'php string comparison'.

 

You'll find what you need, you can take a look at php's function:

http://www.php.net/manual/en/function.similar-text.php

 

It returns the number of matching chars in both strings, which isn't exactly what you want, but I'm sure there is something close enough around there.

 

As far as I know, there is no function in php that will compare two different strings and tell you what ones share the same chars and what are different.

 

Good luck.

Link to comment
Share on other sites

Use count_chars and array_diff

 


<?php

$a = 'abcDEF';
$b = 'EcFabD';

$aChars=count_chars($a, 1);
$bChars=count_chars($b, 1);

if ($aChars==$bChars){
echo "Strings match";
}
else {
echo "No  match";
}

 

[edit]

No need for the array stuff aparently

 

 

Yep, that works great.  It's better than what I was starting to do...

 

$a = "abcDEF";
$b = "abcDEF";

$lenA = strlen($a);
$lenB = strlen($b);


if ($lenA != $lenB)
{
echo "Diff Len, no need to continue.";
exit();
}

$data1 = preg_split("//", $a);
$data2 = preg_split("//", $b);

$len = $lenA;

$found = 0;

for ($x = 1; $x <= $len; $x++)
{
$found = 0;
for ($y = 1; $y <= $len; $y++)
{
	if ($data1[$x] == $data1[$y])
	{
		$found = 1;
		break;
	}
}

if ($found == 0)
	break;
}

if ($found == 0)
echo "No match";

 

Which wasn't quite working anyway.  :)

Link to comment
Share on other sites

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.