3

I have two strings (which are supposed to be the same). One is pulled from an API result and one is entered by the user. I'm trying to compare them and failing. When I var_dump, I get the following:

var_dump($str1);
var_dump($str2);

string(21) "Software & Technology" 
string(25) "Software & Technology"

Notice the incorrect length of $str2. Anyone know what's going on here?

dcaswell
  • 3,137
  • 2
  • 26
  • 25
user1032752
  • 751
  • 1
  • 11
  • 28
  • 1
    They might just be rendered the same. Have you viewed the source in your browser? One of the & might be rendered as & – Michael Thessel Apr 09 '13 at 17:30
  • 1
    Most likely the second string is actually `Software & Technology`, which would display the same as the first one in most browsers. Use `echo htmlspecialchars($str2)` to find out. – Jon Apr 09 '13 at 17:30
  • Thank you for your replies. It doesn't really matter how they render, it matters that the comparison fails. I have tried replacing '&' with '&' in $str2 and the length changes from 26 to 25. How could I get the strings to be the same? – user1032752 Apr 09 '13 at 17:37
  • Are you sure that there aren't any multibyte-whitespaces or invisible characters like acsii < 32? – bwoebi Apr 09 '13 at 17:30
  • mb_strlen also returns the incorrect length of 25 or 26 – user1032752 Apr 09 '13 at 17:38

2 Answers2

11

It appears that you have HTML ampersand character &amp; in one of the string. You should use html_entity_decode before comparing strings:

if (html_entity_decode($str1) == html_entity_decode($str2)) {
    // ...
}

Live Demo: http://ideone.com/pkWEJC

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Your answer helped me out but, from what I read in this question: [String comparison using == vs. strcmp](http://stackoverflow.com/questions/3333353/string-comparison-using-vs-strcmp), you shouldn't use `==` when comparing strings. – Tony Apr 30 '14 at 23:16
0

Using html_entity_decode will address the ampersand (and other character) issues, and using strcmp will take care of the rest.

if (strcmp(html_entity_decode($str1), html_entity_decode($str2)) == 0) {
    // ..
}