Home >Backend Development >PHP Problem >How to delete the beginning string in php

How to delete the beginning string in php

藏色散人
藏色散人Original
2021-05-20 10:36:222117browse

php method to delete the beginning string: 1. Delete through "substr($str, strlen($prefix));"; 2. Through "preg_replace('/^'. preg_quote($prefix, '/') . '/'...)" method to delete.

How to delete the beginning string in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

php Delete a string from the beginning of the string

Specific question:

I have a string that looks like this:

$str = "bla_string_bla_bla_bla";

How do I remove the first bla_; but only if it is in Found the beginning of the string?

Use str_replace(), which deletes all bla_'s.

Method:

Method one:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
}

Requires: 0.0369 ms (0.000,036,954 seconds)

Method two:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

The first run (compile) takes 0.1749 ms (0.000,174,999 seconds), and then 0.0510 ms (0.000,051,021 seconds).

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete the beginning 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