Skip to content
PHP Logo

What are the potential pitfalls of using substr() function in PHP to manipulate data retrieved from a database?

Using the substr() function in PHP to manipulate data retrieved from a database can lead to issues if the length of the data varies or if the data contains special characters that could be cut off incorrectly. To avoid these pitfalls, it's recommended to use functions like mb_substr() for multibyte character support or strlen() to dynamically determine the length of the string before using substr().

php
// Example of using mb_substr() for multibyte character support
$data = $row['column_name']; // Retrieve data from database
$trimmed_data = mb_substr($data, 0, 100, 'UTF-8'); // Trim data to 100 characters
echo $trimmed_data;