Home  >  Article  >  Backend Development  >  How to get the characters after the number in php

How to get the characters after the number in php

青灯夜游
青灯夜游Original
2022-05-26 21:15:271442browse

Two methods: 1. Use the substr() function to intercept English strings, the syntax is "substr(string, starting position, number of characters)"; 2. Use the mb_substr() function to intercept Chinese or Chinese English mixed string, syntax "mb_substr(string, starting position, number of characters, "character encoding")".

How to get the characters after the number in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php provides two methods to extract the string Characters after the number:

  • substr()

  • mb_substr()

##substr () has similar functions to mb_substr(), but substr() is only useful for English strings, while mb_substr() is useful for Chinese, Chinese-English mixed, and English strings.

1. Use the substr() function

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

The parameter description is as follows:

  • $string: the string that needs to be intercepted , the string contains at least one character;

  • $start: intercept the starting position of the string;

  • $length: optional parameter , indicating the length of the intercepted string.

If you want to intercept characters after the Nth digit, $start needs to be set to

N (because characters are counted from 0, N-1 1 =N).

Example:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="Hello world";
echo "原字符串:".$str."<br>";
echo "取第1位之后的一个字符:".substr($str,1,1)."<br>";
echo "取第2位之后的一个字符:".substr($str,2,1)."<br>";
echo "取第3位之后的2个字符:".substr($str,3,2)."<br>";
echo "取第4位之后的全部字符:".substr($str,4)."<br>";
?>

How to get the characters after the number in php

2. Use the mb_substr() function

mb_substr($str , $start [, $length = NULL [, $encoding = mb_internal_encoding()]])

mb_substr() is better than substr( ) function has an additional optional parameter $encoding: indicating the character encoding of $str. If omitted, the internal character encoding is used.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = &#39;php中文网是一个在线学习编程的网站&#39;;
echo "原字符串:".$str."<br>";
echo "取第1位之后的一个字符:".mb_substr($str,1,1,"utf-8")."<br>";
echo "取第2位之后的一个字符:".mb_substr($str,2,1,"utf-8")."<br>";
echo "取第3位之后的2个字符:".mb_substr($str,3,2,"utf-8")."<br>";
?>

How to get the characters after the number in php

Recommended learning: "

PHP Video Tutorial"

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

Statement:
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