Home  >  Article  >  Backend Development  >  Function to intercept string in php

Function to intercept string in php

下次还敢
下次还敢Original
2024-04-29 09:30:24385browse

PHP uses the substr() and mb_substr() functions to intercept strings. The former is suitable for single-byte characters, and the latter supports multi-byte characters. Usage: substr(string, starting position, length); mb_substr(string, starting position, length, encoding). Example: intercept the first 5 characters: substr("Hello World", 0, 5); intercept starting from the 6th character: substr("Hello World", 5); intercept the middle part: substr("Hello World", 2 , 4); Processing multi-byte characters: mb_substr("Hello World",

Function to intercept string in php

PHP function to intercept strings

Goal: Intercept the specified part of the string

Function:

  • substr()
  • mb_substr() (multi-byte characters)

Usage:

substr( )

<code class="php">substr($string, $start, $length);</code>
  • $string:The string to be intercepted
  • $start:Interception starting position (0 means start )
  • $length: Intercept length (optional, intercepted to the end of the string by default)

mb_substr()

<code class="php">mb_substr($string, $start, $length, $encoding);</code>
  • $string:The string to be intercepted
  • $start:Interception starting position (0 means start)
  • $length: Intercept length (optional, default is to intercept to the end of the string)
  • $encoding: Character encoding (optional, default is UTF-8)

Example:

Intercept the first 5 characters of the string:

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

Intercept the string from Starting from the 6th character:

<code class="php">$string = "Hello World";
$result = substr($string, 5); // "World"</code>

Intercept the middle part of the string:

<code class="php">$string = "Hello World";
$result = substr($string, 2, 4); // "llo "</code>

Use mb_substr to process multi-byte characters:

<code class="php">$string = "你好世界";
$result = mb_substr($string, 0, 3, "UTF-8"); // "你好"</code>

The above is the detailed content of Function to intercept 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