0

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

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

4 Comments

what's the fourth parameter do?
Its the count. If i dont specify, it will replace x to do not in the whole string. Or we can tell that how many times we want to replace X in string.
Well that saves making another method called preg_replace_all ;)
Getting expected result??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.