Hi, Guest ~ Login or Register

Replacing words in strings

Replacing words in strings

Listed In Uncategorized » — Viewing Full Tutorial
We're going to learn about the function, str_replace - more info can be found at PHP's manual at this link: http://www.php.net/str_replace

str_replace(what you're looking for, what you wanna replace it with, where you're looking);

So, as an example:

$msg = "Dan is alright.";
$bettermsg = str_replace("alright", "god", $msg);
echo $bettermsg;

This would print: Dan is god.



You can also use it with arrays. Say we had a string full of pointless numbers, this snippet would clean it out for us.

$msg = "1He3l64lo 4w5o865rl1d2.";
$numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
$cleanmsg = str_replace($numbers, "", $msg);
echo $cleanmsg;

This would print: Hello world.


Hope this is of help to people in their scripts and applications. :)

Working Beta

  1. The Forums
    These are mostly functional. If you see any weird bugs, post a thread about it and an administrator will do something.
  2. Tutorial Writing
    You can now submit tutorials to the brand new management system.
  3. Tutorials Home
    View tutorials by categories and search for them here.
  4. Shoutbox
    See below. Registered users only!

Register

Newest User

Say hi to rayjo! rayjo joined on Wednesday, 3rd December.

Sponsor

Shoutbox