从字符串开头删除字符串 [英] Remove a string from the beginning of a string

查看:97
本文介绍了从字符串开头删除字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的字符串:

I have a string that looks like this:

$str = "bla_string_bla_bla_bla";

如何删除第一个bla_;但是只有在字符串的开头才能找到它?

How can I remove the first bla_; but only if it's found at the beginning of the string?

使用str_replace(),它将删除所有 bla_.

推荐答案

无正则表达式的纯格式:

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

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

拍摄时间: 0.0369毫秒(0.000,036,954秒)

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

并且:

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

需要:第一次运行(编译)为 0.1749毫秒(0.000,174,999秒),之后为 0.0510毫秒(0.000,051,021秒).

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

显然是在我的服务器上配置的.

Profiled on my server, obviously.

这篇关于从字符串开头删除字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆