0

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";
}
?>
3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by blocblue
0

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.

Edited by blocblue: n/a

0

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.

Edited by digital-ether: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.