I've no idea which order $r or $str exectues in. Else you could just use regsubex of a str of .'s then randomize each character.
Furthermore, you could randomize between upper, lower case, numbers symbols.. If you have spare time.