Checking if a String in PHP is Composed of Single-Byte Characters

To check if a string in PHP is composed of only single-byte characters, you can specify the string encoding and ensure that the character count (number of characters) matches the byte count.

Source Code

/**
 * Checks if a string consists of only single-byte characters
 * @param string $str The string to check
 * @param string $encodingType The encoding of the string
 * @return bool Returns true if the string consists of only single-byte characters, false otherwise
 */
function isSingleByteString(string $str, string $encodingType = null) {
    if (!$encodingType) {
        $encodingType = mb_internal_encoding();
    }

    if (!canConvertToTargetEncoding($str, $encodingType)) {
        return false;
    }

    return strlen(mb_convert_encoding($str, $encodingType)) === mb_strlen($str);
}

/**
 * Checks if a string can be converted to the specified encoding
 * @param string $str The string to check
 * @param string $targetEncoding The desired target encoding
 * @return bool Returns true if the string can be converted to the specified encoding, false otherwise
 */
function canConvertToTargetEncoding($str, $targetEncoding) {
    $encoded = mb_convert_encoding($str, $targetEncoding);
    $decoded = mb_convert_encoding($encoded, mb_internal_encoding(), $targetEncoding);

    return $str === $decoded;
}

If the string provided to the isSingleByteString function cannot be converted to the specified encoding, the function will return false.

Verification

Specify the string and the encoding you want to check against, then execute the function. If the encoding is omitted, the function will check against UTF-8.

Enter Parameters

isSingleByteString(
 "
,
 ");

Verification Results

Follow me!

photo by:Ivan Shilov