Home  >  Article  >  Backend Development  >  How to remove the specified substring at the beginning of a string in php

How to remove the specified substring at the beginning of a string in php

青灯夜游
青灯夜游Original
2022-06-29 16:19:181358browse

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)".

How to remove the specified substring at the beginning of a string in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = &#39;bla_string_bla_bla_bla&#39;;
echo "原字符串:".$str."<br>";
$prefix = &#39;bla_&#39;;
$str = substr($str, strlen($prefix));
echo "处理后的字符串:".$str;
?>

How to remove the specified substring at the beginning of a string in php

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = &#39;bla_string_bla_bla_bla&#39;;
echo "原字符串:".$str."<br>";
$prefix = &#39;bla_&#39;;
$str = preg_replace(&#39;/^&#39; . preg_quote($prefix, &#39;/&#39;) . &#39;/&#39;, &#39;&#39;, $str);
echo "处理后的字符串:".$str;
?>

How to remove the specified substring at the beginning of a string in php

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!

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