Function to intercept string in php

下次还敢
Release: 2024-04-29 09:30:24
Original
350 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( )

substr($string, $start, $length);
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()

mb_substr($string, $start, $length, $encoding);
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:

$string = "Hello World"; $result = substr($string, 0, 5); // "Hello"
Copy after login

Intercept the string from Starting from the 6th character:

$string = "Hello World"; $result = substr($string, 5); // "World"
Copy after login

Intercept the middle part of the string:

$string = "Hello World"; $result = substr($string, 2, 4); // "llo "
Copy after login

Use mb_substr to process multi-byte characters:

$string = "你好世界"; $result = mb_substr($string, 0, 3, "UTF-8"); // "你好"
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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!