Home >Backend Development >PHP Problem >How to intercept string from digit in php
Interception method: 1. Use the substr() function, the syntax "substr (string, intercept the starting position of the string, intercept the length of the string)"; 2. Use the mb_substr() function, the syntax " mb_substr (string, intercept the starting position of the string, intercept the length of the string, character encoding)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you want to start from the specified location To intercept a string, you can use the substr() and mb_substr() functions.
Both the substr() and mb_substr() functions can intercept strings. The only difference between them is the processing of Chinese characters. Let’s take a look at these two functions.
substr() function intercepts a string
The substr() function can intercept characters of a certain length from a specified position in a string.
Example:
<?php echo substr("Hello world",0,10)."<br>"; echo substr("Hello world",1,8)."<br>"; echo substr("Hello world",0,5)."<br>"; echo substr("Hello world",6,6)."<br><br>"; echo substr("Hello world",0,-1)."<br>"; echo substr("Hello world",-10,-2)."<br>"; echo substr("Hello world",0,-6)."<br>"; echo substr("Hello world",-2-3)."<br><br>"; echo substr("欢迎来到PHP中文网",0,3)."<br>"; ?>
substr() function has no problem processing English, but in development we tend to process more Chinese characters , although the substr() function can also handle Chinese, it is not perfect. So how to intercept Chinese characters? You can use the mb_substr() function.
mb_substr() function intercepts Chinese string
The mb_substr() function can intercept a specified part of a string. Different from the substr() function, The mb_substr() function is not only valid for English characters, but also for Chinese characters.
<?php header("Content-type:text/html;charset=utf-8"); $str = '欢迎访问PHP中文网,一个在线学习编程的网站。'; echo mb_substr($str,0, 4,"utf-8").'<br>'; echo mb_substr($str, -19,strlen($str),"utf-8").'<br>'; echo mb_substr($str, 4, 6,"utf-8").'<br>'; echo mb_substr($str, 4, -16,"utf-8").'<br>'; echo mb_substr($str, -19, -13,"utf-8").'<br>'; echo mb_substr($str, -19, 6,"utf-8").'<br>'; var_dump(mb_substr($str, 40,"utf-8")); echo '<br>'; var_dump(mb_substr($str, 4, null,"utf-8")); ?>
Usage tips:
Use the mb_substr() function to intercept a string of specified length, and replace the excess part with "...".
<?php header("Content-type:text/html;charset=utf-8"); $str = 'php中文网是一个在线学习编程的网站,我们发布了多套文字教程,它们都通俗易懂,深入浅出。'; if(strlen($str)>18){ echo mb_substr($str, 0, 18,"utf-8").'...'; }else{ echo $str; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to intercept string from digit in php. For more information, please follow other related articles on the PHP Chinese website!