if ($str == trim($str) && strpos($str, ' ') !== false) { echo 'has spaces, but not at beginning or end'; }