cast $str to (string) for mb_detect_encoding 

"mb_detect_encoding() expects parameter 1 to be string, object given". Adding (string) prevents errors in the event $str is not a string.