Function to intercept string in php

下次还敢
Release: 2024-04-29 09:30:24
Original
410 people have browsed it

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>
Copy after login
  • $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>
Copy after login
  • $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>
Copy after login

Intercept the string from Starting from the 6th character:

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

Intercept the middle part of the string:

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

Use mb_substr to process multi-byte characters:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template