PHP mb_substr() Tutorial 🎯

beginner
23 min

PHP mb_substr() Tutorial 🎯

Welcome to our PHP mb_substr() tutorial! In this lesson, we'll explore how to use this powerful PHP function to handle multi-byte strings more effectively. By the end of this tutorial, you'll be able to extract substrings with ease and precision. πŸ“ Note: This function is particularly useful when dealing with languages that use multi-byte characters, such as Japanese, Chinese, and Korean (Japanese, Chinese, and Korean are collectively referred to as JCK languages).

What is mb_substr()? πŸ“ Note: mb_substr() is a PHP function that extracts a substring from a multi-byte string.

Why Use mb_substr()? πŸ’‘ Pro Tip: It allows us to work with multi-byte strings more accurately, which is crucial for handling JCK languages.

Getting Started with mb_substr()

Basic Usage πŸ“ Note: mb_substr($string, $start, $length, $encoding) is the syntax for the mb_substr() function.

  • $string: the multi-byte string you want to extract a substring from.
  • $start: the index at which the extraction begins.
  • $length: the number of characters to be extracted.
  • $encoding: the character encoding of the string. This is optional and defaults to UTF-8.

Example: Let's say we have a Japanese sentence: "γ“γ‚“γ«γ‘γ―γ€δΈ–η•ŒοΌ".

php
<?php $japanese_sentence = "γ“γ‚“γ«γ‘γ―γ€δΈ–η•ŒοΌ"; $extracted_substring = mb_substr($japanese_sentence, 0, 5, "UTF-8"); echo $extracted_substring; // Output: こんにけ ?>

In this example, we're extracting the first 5 characters from the Japanese sentence.

Advanced Usage πŸ’‘ Pro Tip: You can also specify the character encoding explicitly to ensure accurate extraction.

Example: Let's say we have a Chinese sentence: "δ½ ε₯½οΌŒδΈ–η•ŒοΌ". If our server is set to a different encoding, we might encounter issues. To avoid this, we can explicitly specify the encoding:

php
<?php $chinese_sentence = "δ½ ε₯½οΌŒδΈ–η•ŒοΌ"; $extracted_substring = mb_substr($chinese_sentence, 0, 2, "GB2312"); echo $extracted_substring; // Output: δ½  ?>

In this example, we're explicitly setting the encoding to GB2312 to ensure accurate extraction.

Quiz

Quick Quiz
Question 1 of 1

What does the `mb_substr()` function do in PHP?

Happy coding! 🎯 Pro Tip: Practice with different languages and character encodings to get a feel for how mb_substr() works in various scenarios.