Home  >  Article  >  Backend Development  >  How to delete the first 5 characters of a string in php

How to delete the first 5 characters of a string in php

PHPz
PHPzOriginal
2023-04-25 18:22:14805browse

Delete the first 5 words and leave the meaningful parts. This is an operation we may do in daily life, but there are similar needs in programming languages. In PHP, we can do this with the help of string functions.

First, we need to understand some commonly used string functions in PHP:

  1. strlen(string): Returns the length of the string.
  2. substr(string, start, length): Returns the substring starting from the specified starting position and having the specified length in the string.
  3. str_replace(search, replace, subject): Find the specified string in the string and replace it with a new string.

Next, let's look at a few examples to demonstrate how to delete several characters in front of a string.

  1. Delete the first 5 characters:
$str = "这是一个字符串";
$str = substr($str, 5);
echo $str; // 输出:"一个字符串"
  1. Delete the first 2 characters:
$str = "这是一个字符串";
$str = substr($str, 2);
echo $str; // 输出:"一个字符串"
  1. Delete the specified characters All previous characters:
$str = "我爱PHP编程";
$char = "P";
$pos = strpos($str, $char);
if ($pos !== false) {
    $str = substr($str, $pos + 1);
}
echo $str; // 输出:"编程"

In the above example, we first use the strpos function to find the position where the specified character appears for the first time in the string, and then use the substr function to intercept the subcharacters from that position. string.

In addition to the method demonstrated above, we can also use the str_replace function to delete several characters in front of the string:

$str = "这是一个字符串";
$remove_str = "这是一";
$str = str_replace($remove_str, '', $str);
echo $str; // 输出:"个字符串"

In this example, we use a substring ($ remove_str) to specify the characters to be removed, and then replaces the found characters with the empty string.

Finally, it is worth noting that the above methods intercept or replace the original string, so if you need to retain the original string, it is recommended to copy it to a temporary variable first, and then proceed operate.

The above is the detailed content of How to delete the first 5 characters of a string 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