How to get last n characters of PHP string

藏色散人
Release: 2023-04-05 11:02:02
Original
4812 people have browsed it

Write a PHP program to get the last n characters of a given string.

How to get last n characters of PHP string

Example:

输入: $str = "HTML!CSS!MySQL!PHP!"
        $n = 4 
输出: PHP!

输入: $str = "HTML!CSS!MySQL!PHP!"
        $n = 10
输出: MySQL!PHP!
Copy after login

Method 1: In this method, iterate over the last N characters of the string and continue adding them appended to a new string.

Example:

<?php 
  
$str = "HTML!CSS!MySQL!PHP!"; 
$n = 4; 
  
$start = strlen($str) - $n;   
$str1 = &#39;&#39;;   
for ($x = $start; $x < strlen($str); $x++) {   
    $str1 .= $str[$x]; 
} 
  
echo $str1; 
?>
Copy after login

Output:

PHP!
Copy after login

Method 2: Another method is to use the built-in library function substr, where the parameter is a string name.

Example:

<?php 
  
$str = "HTML!CSS!MySQL!PHP!"; 
$n = 10;   
$start = strlen($str) - $n; 
$str1 = substr($str, $start); 
  
echo $str1; 
?>
Copy after login

Output:

MySQL!PHP!
Copy after login

Note: In the above example, $start can also use -N to create the last n A substring of characters.

Related recommendations: "PHP Tutorial"http://www.php.cn/course/list/29.html

This article This article is about how to get the last n characters of a PHP string. I hope it will be helpful to friends in need!

The above is the detailed content of How to get last n characters of PHP string. For more information, please follow other related articles on the PHP Chinese website!

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!