Home headlines Summary of php substr function definition and usage (2022)

Summary of php substr function definition and usage (2022)

May 02, 2018 am 10:53 AM
php substr

Summary of php substr function definition and usage (2022)

php substr is a functional function developed based on the PHP language that can return a part of a string. Sometimes when we use php substr, some garbled characters will appear. How to solve it?

php substr basic syntax

string substr ( string $string , int $start [, int $length ] )

Returns a string of length starting from the start position in the string. The substr function intercepts characters by bytes. Chinese characters are 2 bytes in GB2312 encoding and 3 bytes in UTF-8 encoding. Therefore, if Chinese characters are truncated when intercepting a string of specified length, the returned result will be garbled.

php substr Parameters

Required. Specifies a part of the string to be returned.

php substr 返回值

返回提取的子字符串, 或者在失败时返回 FALSE。

php substr 示例

1、基本使用

<?php
echo substr(&#39;abcdef&#39;, 1);     // bcdef
echo substr(&#39;abcdef&#39;, 1, 3);  // bcd
echo substr(&#39;abcdef&#39;, 0, 4);  // abcd
echo substr(&#39;abcdef&#39;, 0, 8);  // abcdef
echo substr(&#39;abcdef&#39;, -1, 1); // f

// 访问字符串中的单个字符
// 也可以使用中括号
$string = &#39;abcdef&#39;;
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f
?>

2、高性能使用

<?php
class apple {
    public function __toString() {
        return "green";
    }
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

php substr 常见问题

1. 如何解决php substr乱码问题

简介:substr函数在截取字符时是按字节来截取的,中文字符在GB2312编码时为2个字节,utf-8编码时为3个字节,所以截取指定长度的字符串时如果截断了汉字,那么返回的结果显示出来便会出现乱码。

2. 关于PHP substr()函数的几个程序

简介:前面小编已经为大家分享了两篇关于phpsubstr()函数的一些用法技巧,现在和大家分享几个用PHP substr()函数写的程序,赶紧来get吧。

3. php substr()函数处理中文详解

简介:substr()函数中文版

4. php substr()函数字符串截取用法实例讲解

简介:这篇文章主要介绍了PHP中substr函数字符串截取用法,结合实例形式分析说明的PHP中substr函数的功能,定义与具体使用技巧,需要的朋友可以参考下

5. php substr()函数的用法

简介:这篇文章主要介绍了php中substr()函数参数说明及用法,以实例形式深入分析了substr()函数中的各个参数的含义,并举例说明了其对应的用法,需要的朋友可以参考下

6. 有关php substr()函数的文章推荐10篇

简介:本文实例讲述了PHP中字符串长度的截取用法。分享给大家供大家参考,具体如下:php中提供了很多使用函数,其中字符串的截取函数也不例外,而且功能也非常强大。<?php//文件编码格式为UTF-8$str='在公园船上,有一个漂亮的女孩,如果在湖中央发生点什么……';echo mb_substr($str,0,7,'UTF-8');//这里设...

7. php substr中文乱码解决办法

简介:php substr中文乱码解决办法

8. PHP substr截取字符串时,中文出现乱码的问题解决

简介::本篇文章主要介绍了PHP substr截取字符串时,中文出现乱码的问题解决,对于PHP教程有兴趣的同学可以参考一下。

9. php substr截断中文半个汉字乱码问题的解决方法

简介:php substr截断中文半个汉字乱码问题的解决方法

10. PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]_PHP教程

简介:PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]。substr --- 取得部份字符串 语法 : string substr (string string, int start [, int length]) 说明 : substr( )传回 string的一部份字符串,由参数 start和 length指定

11. 浅析PHP substr,mb_substr以及mb_strcut的区别和用法_PHP教程

简介:浅析PHP substr,mb_substr以及mb_strcut的区别和用法。PHP substr()函数可以 分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_substr() /mb_strcu

12. PHP substr_replace() function syntax and parameters_PHP tutorial

Introduction: PHP substr_replace() function syntax and parameters. PHP substr_replace() function syntax substr_replace(string,replacement,start,length) Parameter Description string Required. Specifies the string to check. replacement required. Specifies what to insert

13. php substr(),explode(),strrev()_PHP tutorial

Introduction: php substr(),explode(),strrev(). substr(str,start,length); Example: substr(php tutorial is very good language,4,5); The output is is ve; When the length of startstr, the return is (); substr(php is very good language,26 ,5); s

14. php substr_replace replaces the character at the specified position and memory corruption vulnerability_PHP tutorial

Introduction: php substr_replace replaces characters at specified positions and memory corruption vulnerability. PHP tutorial substr_replace replaces characters at specified positions and memory corruption vulnerability Tips and comments Note: If start is a negative number and length is less than or equal to start, length is 0. $username =

15. Introduction to the functions of the PHP Substr library_PHP tutorial

##Introduction: PHP Substr library Function introduction. Beginner The following PHP Substr library function program is not perfect, but there is no problem in processing general Chinese (GB18030, GB2312, BIG5). This function is not suitable for UTF-8 encoded text. //$str characters

16. PHP substr interception of Chinese characters appears garbled problem solving_PHP tutorial

Introduction: PHP substr intercepts Chinese characters and solves the problem of garbled characters. We are using 1. Using the mb_substr interception of the mbstring extension library will avoid garbled characters. 2. Write the interception function yourself, but the efficiency is not as high as using the mbstring extension library. 3. If it is only

17. Explanation on the implementation skills of PHP substr function_PHP tutorial

Introduction: Explanation on the implementation skills of PHP substr function. I just sorted out the usage of the substr function and made a few examples to clear up the confusion for newcomers. Experts please pass by. Let’s first take a look at the syntax of the PHP substr function: string substr(string

##18.

Demonstrating the use of the PHP substr function_PHP tutorial

Introduction: Demonstrate the use of PHP substr function. PHP is the most commonly used language for dynamically developing WEB pages. String processing is the most commonly used in programming. Let’s talk about PHP substr in detail here. There are a bunch of applications similar to

##19.

php substr() function to implement filtering with a mantissa of 4_PHP tutorial

Introduction: The php substr() function implements filtering numbers with mantissas of 4. Today, a customer wants to generate 400 phone numbers in batches. The starting position is 10000. At first, I directly generated numbers such as 10004, but the merchants did not like this. Number, the filtered mantissa is

20.

php substr_replace replace string some examples_PHP tutorial

Introduction : Some examples of php substr_replace replacing strings. Substr_replace is a bit like str_replace, which directly replaces part of the string. Let me introduce to you how to use the substr_replace() function to replace part of the string.

21. php substr() function to intercept Chinese string garbled_PHP tutorial

Introduction: php substr() function to intercept The Chinese string is garbled. In PHP, if I want to use substr() to intercept the string in English, it will be a tragedy. But don’t worry, we can use other methods to solve it. p

22. PHP substr Interception of Chinese garbled problem solution_PHP tutorial

Introduction: Solution to the problem of intercepting Chinese garbled characters with PHP substr. PHP provides us with several character interception functions, including substr, mb_substr, and mb_strcut functions. Some of our PHP beginners will use substr to intercept Chinese characters, but they find that the Chinese characters will be garbled

23. Several application examples of the PHP substr_replace() function_PHP tutorial

Introduction: Several application examples of the PHP substr_replace() function. Introduction to substr_replace() function The substr_replace() function replaces part of a string with another string. Syntax: substr_replace(string,replacement,start,length) parameter string, must

24. Several program applications of PHP substr() function_PHP tutorial

Introduction: Several program applications of PHP substr() function. Introduction to substr() function The substr() function returns a part of a string. Syntax: substr(string,start,length). string: required. Specifies a part of the string to be returned. start: Must

25. php substr,iconv_substr,mb_substr_PHP tutorial

##Introduction: php substr,iconv_substr,mb_substr . When PHP intercepts Chinese strings, it often uses two functions iconv_substr and mb_substr. How to choose between these two functions? You will understand by referring to the examples introduced in this article.

For more PHP related knowledge, please visit PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次还敢
Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1508
276
How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

Building Resilient Microservices with PHP and RabbitMQ Building Resilient Microservices with PHP and RabbitMQ Jul 27, 2025 am 04:32 AM

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

python run shell command example python run shell command example Jul 26, 2025 am 07:50 AM

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Creating Production-Ready Docker Environments for PHP Creating Production-Ready Docker Environments for PHP Jul 27, 2025 am 04:32 AM

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

ParametersDescription
##string
startRequired. Specifies where in the string to begin.

  • Positive numbers - start at the specified position in the string

  • Negative numbers - start at the specified position from the end of the string

  • 0 - Starts at the first character in the string

lengthOptional. Specifies the length of the returned string. The default is until the end of the string.

  • Positive number - the length returned from the position of the

    start parameter

  • Negative number - the length returned from the end of the string length