Replace only the first character of a string with str_replace?

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

$out = ltrim($in, "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".

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 becomes 7
  • 000 becomes 0
  • 100 stays as 100
  • 456 stays as 456
  • 00a becomes 0
  • 56a becomes 0
  • ab4 becomes 0
  • -007 becomes -7

...etc.

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 = '1ere is the solution';
echo preg_replace('/1/', 'h', $str, 1); // outputs 'here is the solution'

Use substr:

$mes2 = substr($mes, 1);

This will remove the first character, which is what it looks like you're trying to achieve. If you want to replace it with something, use this:

$mes2 = $new_char . substr($mes, 1);

Edit

I may have misread your question - if $mes[0] is the original string, use $mes[0] in place of $mes above.