Home  >  Article  >  Backend Development  >  How to Extract the First Five Characters from a String in PHP?

How to Extract the First Five Characters from a String in PHP?

DDD
DDDOriginal
2024-11-07 09:52:03914browse

How to Extract the First Five Characters from a String in PHP?

Truncating Strings: Retrieving the First 5 Characters

This question seeks a solution for extracting the first five characters from a given string in PHP. The provided input string is "HelloWordl", and the desired output should yield "Hello".

Single-Byte Strings

For strings with single-byte characters, such as ASCII or ISO 8859, the substr function can be employed:

<code class="php">$result = substr($myStr, 0, 5);</code>

In this snippet, substr starts (0) and retrieves (5) characters from the string $myStr.

Multi-Byte Strings

For strings with multi-byte characters, such as UTF-8 or UTF-16, mb_substr offers a solution:

<code class="php">$result = mb_substr($myStr, 0, 5);</code>

Similar to substr, mb_substr defines 0 as the starting point and 5 as the length of the extracted characters.

By utilizing either substr or mb_substr, depending on the string's encoding, you can effectively retrieve the first five characters from a given string in PHP.

The above is the detailed content of How to Extract the First Five Characters from a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn