PHP convert_cyr_string Function – Complete Guide
The PHP convert_cyr_string() function is used to convert a string between different Cyrillic character encodings.
This function is mainly useful when working with Russian, Ukrainian, or other Cyrillic-based languages in legacy systems.
In this guide, you’ll learn how it works, syntax, examples, and best practices in a simple and beginner-friendly way.
What is convert_cyr_string() in PHP?
The convert_cyr_string() function converts text from one Cyrillic encoding to another.
Simple idea:
Convert text → from one encoding → to another encoding
Why is it Important?
Different systems use different encodings like:
- Windows-1251
- KOI8-R
- ISO-8859-5
If encodings don’t match, text may look like:Привет instead of Привет
This function helps fix such issues.
Syntax of convert_cyr_string()
string convert_cyr_string(string $str, string $from, string $to)
Parameters Explained
| Parameter | Description |
|---|---|
$str | Input string |
$from | Source encoding |
$to | Target encoding |
Encoding Codes
| Code | Encoding |
|---|---|
| k | KOI8-R |
| w | Windows-1251 |
| i | ISO-8859-5 |
| a | x-cp866 |
| d | x-cp866 |
| m | x-mac-cyrillic |
Basic Example
<?php
$text = "Привет"; // Cyrillic text
$converted = convert_cyr_string($text, 'w', 'k');
echo $converted;
?>Explanation
'w'= Windows-1251'k'= KOI8-R- Converts text between encodings
👉 Output may not display correctly unless encoding matches your browser.
Real-World Use Cases
Fixing Garbled Text
<?php
$text = "Привет";
$fixed = convert_cyr_string($text, 'k', 'w');
?>Working with Legacy Systems
Older applications may use different encodings.
$data = convert_cyr_string($input, 'i', 'w');Data Migration
Convert database data:
$converted = convert_cyr_string($oldData, 'a', 'w');Common Mistakes
Wrong Encoding Codes
❌ Wrong:
✔ Correct:
Using with UTF-8
Important:
This function does NOT support UTF-8
Use iconv() or mb_convert_encoding() instead.
Expecting Encryption
- This is NOT encryption
- It only converts encoding
Advanced Example
<?php
header("Content-Type: text/html; charset=windows-1251");
$text = "Привет мир";
$converted = convert_cyr_string($text, 'k', 'w');
echo $converted;
?>Explanation
- Sets correct browser encoding
- Ensures proper display
- Prevents garbled output
FAQs
What does convert_cyr_string() do?
It converts Cyrillic text between different encodings.
Does it support UTF-8?
No, it only supports specific Cyrillic encodings.
Is this function still used?
Mostly in legacy systems.
What is the best alternative?
Use iconv() or mb_convert_encoding().
Why is my output unreadable?
Because encoding does not match browser or system.