What is the difference between using substr() and preg_replace() to truncate a string in PHP?
When truncating a string in PHP, substr() is a simpler and more efficient option if you only need to cut off a specific number of characters from the beginning or end of the string. On the other hand, preg_replace() is useful when you need to truncate a string based on a specific pattern or regular expression.
// Using substr() to truncate a string
$string = "This is a long string that needs to be truncated.";
$truncated_string = substr($string, 0, 20);
echo $truncated_string;
// Using preg_replace() to truncate a string based on a pattern
$string = "This is a long string that needs to be truncated.";
$truncated_string = preg_replace('/^(.{0,20})\b.*/', '$1', $string);
echo $truncated_string;