What are the best practices for validating the length of a string in PHP, especially when using preg_match?

When validating the length of a string in PHP, especially when using preg_match, it's important to combine both functions to ensure the string meets the desired length criteria. One approach is to use preg_match to check the string against a regular expression pattern that specifies the valid string length range. This can help prevent strings that are too short or too long from passing validation.

// Validate string length using preg_match
function validateStringLength($string, $minLength, $maxLength) {
    $pattern = '/^.{'.$minLength.','.$maxLength.'}$/';
    if(preg_match($pattern, $string)) {
        return true;
    } else {
        return false;
    }
}

// Example usage
$string = "Hello World";
$minLength = 5;
$maxLength = 10;

if(validateStringLength($string, $minLength, $maxLength)) {
    echo "String length is valid.";
} else {
    echo "String length is invalid.";
}