How can special characters from a database be avoided or transformed when using substr function in PHP?

Special characters from a database can be avoided or transformed when using the substr function in PHP by first sanitizing the input data to remove any unwanted characters. This can be done using functions like htmlspecialchars or addslashes to escape special characters. Additionally, using regular expressions to filter out unwanted characters can also help ensure that the substr function operates on clean data.

// Example code to sanitize input before using substr function
$input = $_POST['input']; // Retrieve input from form
$sanitized_input = htmlspecialchars($input); // Sanitize input to remove special characters
$substring = substr($sanitized_input, 0, 10); // Use substr function on sanitized input
echo $substring; // Output the resulting substring