Home >Backend Development >PHP Problem >How to get only the first few characters in php
php method to get only the first few characters: first create a PHP sample file; then define a string; finally intercept the first 3 characters through the "substr($str, 0, 3);" method Can.
The operating environment of this article: Windows7 system, PHP7.1 version, Dell G3 computer
How to get only the first few characters of php ?
Read (intercept substr) the first N characters of the string in PHP or take a few characters starting from the first few characters
<?php $str = "123456789"; echo substr($str , 0 , 3);//从左边第一位字符起截取3位字符:结果:123 echo substr($str , 3 , 3);//从左边第3位字符起截取3位字符:结果:456 ?> <?php $rest = substr("abcdef", -1); // 返回 "f" $rest = substr("abcdef", -2); // 返回 "ef" $rest = substr("abcdef", -3, 1); // 返回 "d" ?>
<?php $rest = substr("abcdef", 0, -1); // 返回 "abcde" $rest = substr("abcdef", 2, -1); // 返回 "cde" $rest = substr("abcdef", 4, -4); // 返回 "" $rest = substr("abcdef", -3, -1); // 返回 "de" ?>
<?php echo substr('abcdef', 1); // bcdef echo substr('abcdef', 1, 3); // bcd echo substr('abcdef', 0, 4); // abcd echo substr('abcdef', 0, 8); // abcdef echo substr('abcdef', -1, 1); // f // 访问字符串中的单个字符 // 也可以使用中括号 $string = 'abcdef'; echo $string[0]; // a echo $string[3]; // d echo $string[strlen($string)-1]; // f ?>
Intercepting and obtaining the length of Chinese strings mb_substr()
$str = '我abc是谁'; //utf-8编码的字符串 echo mb_substr($str, 0, 2, 'utf-8'); //输出 我a $str = '我是谁'; //gbk编码的字符串 echo mb_substr($str, 0, 1, 'gbk'); //输出 我
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get only the first few characters in php. For more information, please follow other related articles on the PHP Chinese website!