Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP String Comparison

I have two strings that look the same when I echo them, but when I var_dump() them they are different string types:

Echo:
http://blah
http://blah
var dump:
string(14) "http://blah"
string(11) "http://blah"
strToHex:
%68%74%74%70%3a%2f%2f%62%6c%61%68%00%00%00
%68%74%74%70%3a%2f%2f%62%6c%61%68

When I compare them they return false. How can I manipulate the string type so that I can perform a comparison that returns true. What is the difference between string 11 and string 14? I am sure there is a simple resolution but have not found anything yet, no matter how I implode, explode, UTF8 encode etc the strings they will not compare or change type.

Thanks for your help!

Peter.

like image 484
paj Avatar asked Jul 12 '11 11:07

paj


4 Answers

Letter "a" can be written in another encoding.
For example: blаh - here a is a cyrillic 'а'.
All of these letters are cyrillic but looks like latin: у, е, х, а, р, о, с

like image 153
OZ_ Avatar answered Nov 15 '22 18:11

OZ_


Trim the strings before comparing, there are Escaped characters, like \t and \n which are not visible.

$clean_str = trim($str);

like image 34
Pheonix Avatar answered Nov 15 '22 20:11

Pheonix


When using var_dump(), then string(14) means that value is string that holds 14 bytes. So string(11) and string(14) are not different "types" of strings, they are just strings of different length.

I would use something like this to see what actually is inside those strings:

function strToHex($value, $prefix = '') {
    $result = '';
    $length = strlen($value);
    for ( $n = 0; $n < $length; $n++ ) {
        $result .= $prefix . sprintf('%02x', ord($value[$n]));
    }
    return $result;
}

echo strToHex("test\r\n", '%');

Output:

%74%65%73%74%0d%0a

This decodes as:

  • %74 - t
  • %65 - e
  • %73 - s
  • %74 - t
  • %0d - \r (carriage return)
  • %0a - \n (line feed)

Or, as pointed out in comments by @Karolis, you can use built-in function bin2hex():

echo bin2hex("test\r\n");

Output:

746573740d0a
like image 35
binaryLV Avatar answered Nov 15 '22 19:11

binaryLV


Have you already tried to trim these strings?

if (trim($string1) == trim($string2)) {
 // do things
}
like image 27
VAShhh Avatar answered Nov 15 '22 20:11

VAShhh