1

Say I hate the word "hat". I want a function that would work something like strreplace("hat", 1, "o") therefore changing it into hot instead of hat.

Is there a way to do this with a function? Or do I have to write my own?

5
  • You have to write your own :) Commented Feb 16, 2013 at 20:58
  • $foo = 'hat'; $foo[1] = 'o'; Commented Feb 16, 2013 at 20:58
  • That only works for single characters, not for strings. Commented Feb 16, 2013 at 20:59
  • substr_replace was what I was looking for. Thanks though. Commented Feb 16, 2013 at 20:59
  • I did not know about that function, good you found your own answer. Commented Feb 16, 2013 at 21:03

3 Answers 3

1
function changeChar($string,$newchar,$pos){
  $string[$pos] = $newchar;
  return $string;
}

echo changeChar("Logs","L",2);

Would echo "LoLs"

Logs
0123 <position (g is the 2nd character ;)

insert this just below the first line if you want the first character to be the 1st not 0th:

$pos = $pos + 1;
Sign up to request clarification or add additional context in comments.

Comments

0
    <?php
function myReplacing($theString, $theCharacter, $thePosition)
{
    return substr_replace($theString, $theCharacter, $thePosition, 1);
}

$a = "test";
$a = myReplacing($a, "u", 1);
echo $a;

    ?>

Comments

0

All you need is str_replace(). See here:http://www.php.net/manual/en/function.str-replace.php

e.g.

echo str_replace("a", "o", "hat");
// outputs 'hot'

Comments

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.