Home > Article > Backend Development > What are the methods to intercept strings in php
php interception method: 1. Use substr() to intercept, you can intercept a certain length of characters from the specified position of the string; 2. Use mb_substr() to intercept, this function can intercept the specified characters from a string Part of it is not only valid for English characters, but also valid for Chinese characters.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
1. Use substr() to intercept String
substr() function can intercept characters of a certain length from the specified position of the string. This intercepted character can be called a "substring" or "substring". Its syntax The format is as follows:
substr($string, $start [, $length])
Parameter description is as follows:
Example: Using start and length parameters with different positive and negative numbers
<?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>"; 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>"; ?>
Output:
Hello worl ello wor Hello world Hello worl ello wor Hello world
2. Use mb_substr() to intercept Chinese strings
The mb_substr() function can intercept a specified part of a string. Unlike the substr() function, the mb_substr() function not only English characters are valid, and Chinese characters are also valid. The syntax format is as follows:
mb_substr($str , $start [, $length = NULL [, $encoding = mb_internal_encoding()]])
Parameter description is as follows:
Example: Use the mb_substr() function to intercept a Chinese string of specified length
<?php $str = '欢迎访问PHP中文网,一个在线学习编程的网站。'; echo mb_substr($str, 4).'<br>'; echo mb_substr($str, -19).'<br>'; echo mb_substr($str, 4, 6).'<br>'; echo mb_substr($str, 4, -16).'<br>'; echo mb_substr($str, -19, -13).'<br>'; echo mb_substr($str, -19, 6).'<br>'; var_dump(mb_substr($str, 40)); echo '<br>'; var_dump(mb_substr($str, 4, null)); ?>
The running results are as follows:
PHP中文网,一个在线学习编程的网站。 PHP中文网,一个在线学习编程的网站。 PHP中文网 PHP PHP中文网 PHP中文网 string(0) "" string(55) "PHP中文网,一个在线学习编程的网站。"
Recommended learning: "PHP Video tutorial》
The above is the detailed content of What are the methods to intercept strings in php. For more information, please follow other related articles on the PHP Chinese website!