只用 str_replace 替换字符串的第一个字符? [英] Replace only the first character of a string with str_replace?

查看:27
本文介绍了只用 str_replace 替换字符串的第一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图只替换字符串的第一个字符,但它不起作用,它替换了字符串上的所有0",这是我的代码:

I'm trying to replace only the first character of a string, but it isn't working, it replaces all the "0" on the string, here's my code:

$mes2 = str_replace('0', '', $mes[0]);

我只想替换第一个字符,如果它是 0,例如:

I want to replace the first character only if its a 0, example:

07 变成 7

我不想一直替换,例如:

I don't want to replace all the time, example:

11 变成 1,我不要.

11 becomes 1, i don't want it.

我也尝试过这种方式,但它没有按照我想要的方式工作,因为如果第二个字符为 0,它也会替换第二个字符,例如 10 变为 1.

I also tried this way, but it didn't work the way i want, because it's replacing also the second character if it's 0, like 10 becomes 1.

$mes2 = preg_replace('/0/', '', $mes, 1);

推荐答案

好的,基于对您问题的改进,您可能想要的是 ltrim.

OK, based on refinements to your question, what you probably want is ltrim.

$out = ltrim($in, "0");

这将从 $in 中去除所有前导零.它不会从其他任何地方删除零,也不会删除除零以外的任何内容.当心;如果你给它000",你会得到"而不是0".

This will strip all leading zeroes from $in. It won't remove zeroes from anywhere else, and it won't remove anything other than zeroes. Be careful; if you give it "000" you'll get back "" instead of "0".

您可以改用类型转换,只要 $in 始终是一个数字(或者如果不是,您希望它产生 0):

You could use typecasting instead, as long as $in is always a number (or you want it to result in 0 if it isn't):

$out = (int) $in;

  • 007 变成 7
  • 000 变为 0
  • 100 保持为 100
  • 456 保持为 456
  • 00a 变为 0
  • 56a 变为 0
  • ab4 变为 0
  • -007 变成 -7
  • ...等等

    现在,万一您只想替换第一个 0,例如007"变为07",那么您在问题中提到的最新尝试几乎就在那里.您只需要添加一个插入符号"字符以确保它只匹配字符串的开头:

    Now, in the unlikely event that you only want to replace the first 0, so for example "007" becomes "07", then your latest attempt mentioned in your question is almost there. You just need to add a "caret" character to make sure it only matches the start of the string:

    $out = preg_replace('/^0/', '', $in);
    

    这篇关于只用 str_replace 替换字符串的第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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