How can PHP developers efficiently check for the presence of a substring in a string of unknown length and replace it with another substring?

When checking for the presence of a substring in a string of unknown length and replacing it with another substring in PHP, developers can use the `strpos()` function to find the position of the substring within the string. If the substring is found, they can then use the `substr_replace()` function to replace it with the desired substring. This approach allows for efficient checking and replacement of substrings in strings of varying lengths.

$string = "This is a sample string";
$substring = "sample";
$replacement = "example";

if(strpos($string, $substring) !== false) {
    $string = substr_replace($string, $replacement, strpos($string, $substring), strlen($substring));
}

echo $string;