Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

portable-utf8

> DevOps
Open source

Portable UTF-8 library - performance optimized (unicode) string functions for PHP.

520 stars0 likes0 views
WebsiteGitHub

About

Portable UTF-8 library - performance optimized (unicode) string functions for PHP.

Portable UTF-8

Description

It is written in PHP (PHP 7.1+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your server.

The benefit of Portable UTF-8 is that it is easy to use, easy to bundle. This library will also auto-detect your server environment and will use the installed php-extensions if they are available, so you will have the best possible performance.

As a fallback we will use Symfony Polyfills, if needed. (https://github.com/symfony/polyfill)

The project based on ...

  • Hamid Sarfraz's work - portable-utf8
  • Nicolas Grekas's work - tchwork/utf8
  • Behat's work - Behat/Transliterator
  • Sebastián Grignoli's work - neitanod/forceutf8
  • Ivan Enderlin's work - hoaproject/Ustring
  • and many cherry-picks from "GitHub"-gists and "Stack Overflow"-snippets ...

Demo

Here you can test some basic functions from this library and you can compare some results with the native php function results.

  • encoder.suckup.de

Index

  • Alternative
  • Install
  • Why Portable UTF-8?
  • Requirements and Recommendations
  • Warning
  • Usage
  • Class methods
  • Unit Test
  • License and Copyright

Alternative

If you like a more Object Oriented Way to edit strings, then you can take a look at voku/Stringy, it's a fork of "danielstjules/Stringy" but it used the "Portable UTF-8"-Class and some extra methods.

php
// Standard library
strtoupper('fòôbàř');       // 'FòôBàř'
strlen('fòôbàř');           // 10

// mbstring 
// WARNING: if you don't use a polyfill like "Portable UTF-8", you need to install the php-extension "mbstring" on your server
mb_strtoupper('fòôbàř');    // 'FÒÔBÀŘ'
mb_strlen('fòôbàř');        // '6'

// Portable UTF-8
use voku\helper\UTF8;
UTF8::strtoupper('fòôbàř');    // 'FÒÔBÀŘ'
UTF8::strlen('fòôbàř');        // '6'

// voku/Stringy
use Stringy\Stringy as S;
$stringy = S::create('fòôbàř');
$stringy->toUpperCase();    // 'FÒÔBÀŘ'
$stringy->length();         // '6'

Install "Portable UTF-8" via "composer require"

bash
composer require voku/portable-utf8

If your project do not need some of the Symfony polyfills please use the replace section of your composer.json. This removes any overhead from these polyfills as they are no longer part of your project. e.g.:

json
{
  "replace": {
    "symfony/polyfill-php72": "1.99",
    "symfony/polyfill-iconv": "1.99",
    "symfony/polyfill-intl-grapheme": "1.99",
    "symfony/polyfill-intl-normalizer": "1.99",
    "symfony/polyfill-mbstring": "1.99"
  }
}

Why Portable UTF-8?

PHP 5 and earlier versions have no native Unicode support. To bridge the gap, there exist several extensions like "mbstring", "iconv" and "intl".

The problem with "mbstring" and others is that most of the time you cannot ensure presence of a specific one on a server. If you rely on one of these, your application is no more portable. This problem gets even severe for open source applications that have to run on different servers with different configurations. Considering these, I decided to write a library:

Requirements and Recommendations

  • No extensions are required to run this library. Portable UTF-8 only needs the PCRE library, which is available by default and cannot be disabled in supported PHP versions.
  • PHP 7.1 is the current minimum requirement. If you need support for older PHP versions, Composer will resolve an older Portable UTF-8 release for you.
  • PHP 8.0 support is also available and will adapt the behaviours of the native functions.
  • To speed up string handling, it is recommended that you have "mbstring" or "iconv" available on your server, as well as the latest version of PCRE library
  • Although Portable UTF-8 is easy to use; moving from native API to Portable UTF-8 may not be straight-forward for everyone. It is highly recommended that you do not update your scripts to include Portable UTF-8 or replace or change anything before you first know the reason and consequences. Most of the time, some native function may be all what you need.
  • There is also a shim for "mbstring", "iconv" and "intl", so you can use it also on shared webspace.

Usage

Example 1: UTF8::cleanup()

php
  echo UTF8::cleanup('�Düsseldorf�');
  
  // will output:
  // Düsseldorf

Example 2: UTF8::strlen()

php
  $string = 'string with utf-8 chars åèä - doo-bee doo-bee dooh';

  echo strlen($string) . "\n
";
  echo UTF8::strlen($string) . "\n
";

  // will output:
  // 70
  // 67

  $string_test1 = strip_tags($string);
  $string_test2 = UTF8::strip_tags($string);

  echo strlen($string_test1) . "\n
";
  echo UTF8::strlen($string_test2) . "\n
";

  // will output:
  // 53
  // 50

Example 3: UTF8::fix_utf8()

php

  echo UTF8::fix_utf8('Düsseldorf');
  echo UTF8::fix_utf8('ä');
  
  // will output:
  // Düsseldorf
  // ä

Portable UTF-8 | API

The API from the "UTF8"-Class is written as small static methods that will match the default PHP-API.

Class methods

access add_bom_to_string array_change_key_case between

binary_to_str bom callback char_at

chars checkForSupport chr chr_map

chr_size_list chr_to_decimal chr_to_hex chunk_split

clean cleanup codepoints collapse_whitespace

count_chars css_identifier css_stripe_media_queries ctype_loaded

decimal_to_chr decode_mimeheader emoji_decode emoji_encode

emoji_from_country_code encode encode_mimeheader extract_text

file_get_contents file_has_bom filter filter_input

filter_input_array filter_var filter_var_array finfo_loaded

first_char fits_inside fix_simple_utf8 fix_utf8

getCharDirection getSupportInfo getUrlParamFromArray get_file_type

get_random_string get_unique_string has_lowercase has_uppercase

has_whitespace hex_to_chr hex_to_int html_encode

html_entity_decode html_escape html_stripe_empty_tags htmlentities

htmlspecialchars iconv_loaded int_to_hex intlChar_loaded

intl_loaded is_alpha is_alphanumeric is_ascii

is_base64 is_binary is_binary_file is_blank

is_bom is_empty is_hexadecimal is_html

is_json is_lowercase is_printable is_punctuation

is_serialized is_uppercase is_url is_utf8

is_utf16 is_utf32 json_decode json_encode

json_loaded lcfirst lcwords levenshtein

ltrim max max_chr_width mbstring_loaded

min normalize_encoding normalize_line_ending normalize_msword

normalize_whitespace ord parse_str pcre_utf8_support

range rawurldecode regex_replace remove_bom

remove_duplicates remove_html remove_html_breaks remove_ileft

remove_invisible_characters remove_iright remove_left remove_right

replace replace_all replace_diamond_question_mark rtrim

showSupport single_chr_html_encode spaces_to_tabs str_camelize

str_capitalize_name str_contains str_contains_all str_contains_any

str_dasherize str_delimit str_detect_encoding str_ends_with

str_ends_with_any str_ensure_left str_ensure_right str_humanize

str_iends_with str_iends_with_any str_insert str_ireplace

str_ireplace_beginning str_ireplace_ending str_istarts_with str_istarts_with_any

str_isubstr_after_first_separator str_isubstr_after_last_separator str_isubstr_before_first_separator str_isubstr_before_last_separator

str_isubstr_first str_isubstr_last str_last_char str_limit

str_limit_after_word str_limit_in_byte str_longest_common_prefix str_longest_common_substring

str_longest_common_suffix str_matches_pattern str_obfuscate str_offset_exists

str_offset_get str_pad str_pad_both str_pad_left

str_pad_right str_repeat str_replace_beginning str_replace_ending

str_replace_first str_replace_last str_shuffle str_slice

str_snakeize str_sort str_split str_split_array

str_split_pattern str_starts_with str_starts_with_any str_substr_after_first_separator

str_substr_after_last_separator str_substr_before_first_separator str_substr_before_last_separator str_substr_first

str_substr_last str_surround str_titleize str_titleize_for_humans

str_to_binary str_to_lines str_to_words str_truncate

str_truncate_safe str_underscored str_upper_camelize str_word_count

strcasecmp strcmp strcspn string

string_has_bom strip_tags strip_whitespace stripos

stripos_in_byte stristr strlen strlen_in_byte

strnatcasecmp strnatcmp strncasecmp strncmp

strpbrk strpos strpos_in_byte strrchr

strrev strrichr strripos strripos_in_byte

strrpos strrpos_in_byte strspn strstr

strstr_in_byte strtocasefold strtolower strtoupper

strtr strwidth substr substr_compare

substr_count substr_count_in_byte substr_count_simple substr_ileft

substr_in_byte substr_iright substr_left substr_replace

substr_right swapCase symfony_polyfill_used tabs_to_spaces

titlecase to_ascii to_boolean to_filename

to_int to_iso8859 to_string to_utf8

to_utf8_string trim ucfirst ucwords

urldecode utf8_decode utf8_encode whitespace_table

words_limit wordwrap wordwrap_per_line ws

access(string $str, int $pos, string $encoding): string

↑ Return the character at the specified position: $str[1] like functionality.

EXAMPLE: UTF8::access('fòô', 1); // 'ò'

Parameters:

  • string $str A UTF-8 string.
  • int $pos The position of character to return.
  • string $encoding [optional] Set the charset for e.g. "mb_" function

Return:

  • string Single multi-byte character.

add_bom_to_string(string $str): non-empty-string

↑ Prepends UTF-8 BOM character to the string and returns the whole string.

INFO: If BOM already existed there, the Input string is returned.

EXAMPLE: UTF8::add_bom_to_string('fòô'); // "\xEF\xBB\xBF" . 'fòô'

Parameters:

  • string $str The input string.

Return:

  • non-empty-string The output string that contains BOM.

array_change_key_case(array $array, int $case, string $encoding): string[]

↑ Changes all keys in an array.

Parameters:

  • array $array The array to work on
  • `int $case [optional] Either CASE_UPPER

or CASE_LOWER (default) `

  • string $encoding [optional] Set the charset for e.g. "mb_" function

Return:

  • string[] An array with its keys lower- or uppercased.

between(string $str, string $start, string $end, int $offset, string $encoding): string

↑ Returns the substring between $start and $end, if found, or an empty string. An optional offset may be supplied from which to begin the search for the start string.

Parameters:

  • string $str
  • string $start Delimiter marking the start of the substring.
  • string $end Delimiter marking the end of the substring.
  • int $offset [optional] Index from which to begin the search. Default: 0
  • string $encoding [optional] Set the charset for e.g. "mb_" function

Return:

  • string

binary_to_str(string $bin): string

↑ Convert binary into a string.

Parameters:

  • string $bin 1|0

Return:

  • string

bom(): non-empty-string

↑ Returns the UTF-8 Byte Order Mark Character.

INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values

EXAMPLE: UTF8::bom(); // "\xEF\xBB\xBF"

Parameters: nothing

Return:

  • non-empty-string UTF-8 Byte Order Mark.

callback(callable(string): string $callback, string $str): string[]

↑

Parameters:

  • callable(string): string $callback
  • string $str

Return:

  • string[]

char_at(string $str, int $index, string $encoding): string

↑ Returns the character at $index, with indexes starting at 0.

Parameters:

  • string $str The input string.
  • int $index Position of the character.
  • `string $encoding [optional] Default

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPasciihacktoberfestmultibytemultibyte-strings

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理