Home >Backend Development >PHP Problem >How to delete the first 5 characters of a string in php
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:
Next, let's look at a few examples to demonstrate how to delete several characters in front of a string.
$str = "这是一个字符串"; $str = substr($str, 5); echo $str; // 输出:"一个字符串"
$str = "这是一个字符串"; $str = substr($str, 2); echo $str; // 输出:"一个字符串"
$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!