Two methods: 1. Use strlen() to get the length of the substring (number of characters), and then use substr() to delete the specified number of characters from the head of the string. The syntax "substr (String,strlen(specified substring))". 2. Use the preg_replace() and preg_quote() functions to replace the starting substring with a null character. The syntax is "preg_replace('/^'.preg_quote(specified substring,'/').'/','', character string)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php Two ways to remove the specified substring at the beginning of a string
Method 1: Use the substr() and strlen() functions to remove
Use strlen() to get the length of the substring
Use substr() to delete the specified number of characters from the head of the string (the number is equal to the length of the substring)
<?php header('content-type:text/html;charset=utf-8'); $str = 'bla_string_bla_bla_bla'; echo "原字符串:".$str."<br>"; $prefix = 'bla_'; $str = substr($str, strlen($prefix)); echo "处理后的字符串:".$str; ?>
Method 2: Use the preg_replace() and preg_quote() functions to replace the beginning substring with an empty character.
# The preg_replace function performs a regular expression search and replace.
preg_last_error function is used to escape regular expression characters.
<?php header('content-type:text/html;charset=utf-8'); $str = 'bla_string_bla_bla_bla'; echo "原字符串:".$str."<br>"; $prefix = 'bla_'; $str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str); echo "处理后的字符串:".$str; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the specified substring at the beginning of a string in php. For more information, please follow other related articles on the PHP Chinese website!