Replacing Spaces with Underscores

$name = str_replace(' ', '_', $name);

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);