jessica
jessica

Reputation: 1687

Replacing the first character of a string with another string

I'm trying to replace the first character of a string with words, but I'm running into some trouble here. I'm only able to replace the character with the first character of the string, and not the entire string. How would I fix this?

$type = "xgo xgo xgo";
$ifX = $type[0];

if ($ifX == "x") {
$type[0] = "do not ";
}

Result:

dgo xgo xgo

Want Result:

do not go xgo xgo

Upvotes: 0

Views: 57

Answers (1)

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

Try this,

$type = "xgo xgo xgo";
echo preg_replace('/x/', 'do not ', $type, 1); // output : do not go xgo xgo

If you dont specity 4th parameter, your output looks like this

do not go do not go do not go// all x are replaced.

Upvotes: 1

Related Questions