What is the correct way to replace spaces with commas in PHP?

To replace spaces with commas in PHP, you can use the str_replace function. This function allows you to specify the string you want to replace, the string you want to replace it with, and the original string. In this case, you would replace spaces with commas in the original string.

<?php
$string = "This is a sample string";
$comma_separated = str_replace(" ", ",", $string);
echo $comma_separated;
?>