Hi All,

im trying to find a way of checking a string to see if it contains a word held in an array. If it is in the array i would like it to be replaced with cencored.

the code if been working with is

<?php
$myString = "Hello, there!";
if ( strstr( $myString, 'Goodbye' ) ) {
  echo "Text found";
} else {
  echo "Text not found";
}
?>

Recommended Answers

All 4 Replies

Hi,

A really simple way to do this would be the following:

// Array containing profane words
$arrProfanities = array('these', 'are', 'the', 'words', 'I', 'want', 'to', 'filter');

// String containing content you want to filter for profane words
$strContent = 'does this string contain any words I want to filter?';

// This will replace all the words from the array that are matched in the string with [censored]
$strContent = preg_replace($arrProfanities, '[censored]', $strContent);

// Output would be:
// $strContent = 'does this string contain any [censored] [censored] [censored] [censored] [censored]?';

Hope this helps.

R.

hi,

thanks for this, works perfectly

Instead of using preg_replace() use str_replace(). It a lot faster. If you need regular expression functionality, then you'd have to use preg_replace.

Digital-ether is correct. I forgot about good old str_replace.

R.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.