What is the best method to convert spaces to underscores in PHP?

To convert spaces to underscores in PHP, you can use the str_replace() function to replace all spaces with underscores in a given string. This function takes three parameters: the search string (in this case, a space), the replacement string (underscore), and the input string. By using str_replace(), you can easily convert spaces to underscores in PHP.

$input = "Hello World";
$output = str_replace(' ', '_', $input);
echo $output; // Output: Hello_World