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
https://forums.phpfreaks.com/topic/249493-compare-chars-in-a-string/
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.

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

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.  :)

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.