What are potential pitfalls when using substr_replace in PHP for text manipulation?
Potential pitfalls when using substr_replace in PHP for text manipulation include not accounting for the length of the replacement string, which can shift the positions of subsequent characters in the string. To avoid this issue, always ensure that the replacement string is the same length as the substring being replaced.
// Example of using substr_replace with proper length handling
$string = "Hello, world!";
$replacement = "everyone";
$substring = "world";
$start = strpos($string, $substring);
$length = strlen($substring);
if ($start !== false) {
$string = substr_replace($string, $replacement, $start, $length);
}
echo $string; // Output: Hello, everyone!