Lowercase second character in a string php

Viewed 237

I have a string that looks like this:

[House-3-BLUE]

I want to convert it, using PHP, to:

[house-3-BLUE]

This seems like it should be simple, but I can't figure out how to do it after looking at a dozen examples.

2 Answers

This would probably work here, and regular expression might not be required:

$str = "[House-3-BLUE]";
echo "[" . strtolower(substr($str, 1, 1)) . substr($str, 2);

Output

[house-3-BLUE]

Advice

It should probably be easier ways to do so, such as Dharman's advice:

You should use lcfirst then

$str = "[House-3-BLUE]";
echo "[" . lcfirst(substr($str, 1));

You can use substr_replace.

$str = "[House-3-BLUE]";
echo substr_replace($str, strtolower(substr($str, 1, 1)), 1, 1);

Try it online: https://3v4l.org/oDoXB

To make the same, but ensure it is Unicode-safe you need to split the string into 3 parts using mb_substr and then concatenate it back into whole string:

$str = "House-3-BLUE]";
echo mb_substr($str,0,1) . mb_strtolower(mb_substr($str,1,1)) . mb_substr($str,2);

Try it online: https://3v4l.org/NYe0r

Related