Thursday, July 24, 2008

String Replacing with PHP

Tutorial name: Text Filtering with PHP
You're experience: Advanced
Difficulty: Novice
Time Taken: 20-60 seconds
Plug-ins needed: none.

Replacing strings with other strings is fairly easy, and the following code will show you how to do so.
$string = "I like you";
echo $string . "\n";
$string = str_replace("like", "love", $string); //str_replace(what to change, what to change to, the input);
echo $string . "\n"; // you will end up with, "i love you"

Now to be a bit creative

$patterns = array(":)", ":(", ":O", "Wow...");
$replacements = array("I'm Happy!", "I'm Sad", "I'm Shocked!", "OMFG that was AMAZING, like WOW!");
$string = "I am a very good actor! :), :(, :O, they loved it, everyone said, \"Wow...\"\n";
echo $string;
$string = str_replace($patterns, $replacements, $string);
echo $string;
// it should end up as, "I am a very good actor! I'm Happy!, I'm Sad, I'm Shocked!, they loved it, everyone said,
// "OMFG that was AMAZING, like WOW!"

No comments: