for the search, my way to preload images! haha

Search for in

Filtering text

PHP Coding Tutorials | Submited Apr 8, 2008

Written by: User Picture..

This shows you how you can filter out certain strings of text using a function and str_replace.


- The code -


Of course, we'll start out with the opening <?php tags, and the first function.

<?php

function filterThese($string){ //Begin the function.

$badwords = array("hell", "damn", "fart"); //This is an array of the curse words, it's pretty simple, eh?

$filtered = str_replace($badwords, "[filtered]", $string); //This replaces the bad words in the array with text of your choice.

return $filtered; //Return the filtered text.
} //End the function.

$filteredText = filterThese($badword); //This calls the function

echo '$filteredText';

?>


- The Explanation -


function filterThese($string){


This opens the function that'll filter the bad words that you define in the array below.

$badwords = array("hell", "damn", "fart");


That's the array where you put whatever you want filtered. If you look, you can see a pattern: "word", "next word".
Use that pattern to add more words.

$filtered = str_replace($badwords, "[filtered]", $string);


$filtered is the variable for the filtered words, str_replace is a PHP function that replaces text; 'str' is short for 'string'. That's how I remember it, anyway.
First putting $badwords means that you want to replace whatever text was a part of THAT variable. Next comes [filtered], [filtered] is the word I just to replace $badwords with. $string is what we put at the beginning of the function, remember?

return $filtered;


This returns What you defined in the $filtered variable, where you replaced the text.

}


This, umm, ends the filterThese function.

$filteredText - filterThese($badword);


This creates a variable from the function, only instead of $string, we use $badwords. That makes sense, right?

echo '$filteredText';


This echos the filtered text. If you know anyything about PHP, you know what echo does.

[fin]


That's it. Hopefully you learned something, even if it wasn't what the tutorial was for. :)

tags Tags: filters replace bad words php

3Thumbs up  Thumbs down0

Related Tutorials
Image filters for IE
Blog images
Replace section headers
Randomness with PHP
Replace proInfo with image
Two Default Pictures
Filtering text
Easy-updating
Alternative to if /else statements
Creating "Your IP is" images
No Comments Found
Sorry, you have to be a member to comment tutorials