How to intercept the first few characters in php

藏色散人
Release: 2023-03-04 07:38:01
Original
5257 people have browsed it

How to intercept the first few characters in php: 1. Use the "substr($str, 0, 3);" method to intercept 3 characters starting from the first character on the left; 2. Use "mb_substr( $str, 0, 2, 'utf-8');" method intercepts Chinese strings.

How to intercept the first few characters in php

Recommended: "PHP Video Tutorial"

Read (intercept substr) the first N characters of a string in PHP Characters or how many characters to start from

<?php 
$str = "123456789";
echo substr($str , 0 , 3);//从左边第一位字符起截取3位字符:结果:123
echo substr($str , 3 , 3);//从左边第3位字符起截取3位字符:结果:456
?>
Copy after login
<?php
$rest = substr("abcdef", -1);    // 返回 "f"
$rest = substr("abcdef", -2);    // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"
?>
Copy after login

<?php
$rest = substr("abcdef", 0, -1);  // 返回 "abcde"
$rest = substr("abcdef", 2, -1);  // 返回 "cde"
$rest = substr("abcdef", 4, -4);  // 返回 ""
$rest = substr("abcdef", -3, -1); // 返回 "de"
?>
Copy after login

<?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
?>
Copy after login

Chinese string interception and length mb_substr()

$str = &#39;我abc是谁&#39;;  //utf-8编码的字符串
echo mb_substr($str, 0, 2, &#39;utf-8&#39;); //输出 我a
 
$str = &#39;我是谁&#39;;  //gbk编码的字符串
echo mb_substr($str, 0, 1, &#39;gbk&#39;); //输出 我
Copy after login

The above is the detailed content of How to intercept the first few characters in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
Popular Tutorials
More>
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!