There are a couple of different ways to do it dependant on exactly what you need to acheive....
you could use str_replace then compare the new string with the old string to see if anything was replaced....
Code: Select all
$search = array('''', '"', '*');
$old_string = 'Here is "some" string**';
$new_string = str_replace($search, '', $old_string);
if ($new_string != $old_string)
{
// strings are different something has been replaced
}
If you need a count of how many have been replaced.....
Code: Select all
$search_string = 'Here is "a" string **';
$search_chars = array('/''/', '/"/', '/\*/');
$counter = 0;
function counter()
{
global $counter;
$counter++;
return;
}
$new = preg_replace_callback($search_chars, 'counter', $search_string);
echo $counter;
The value of $counter when echoed should be 4
Unfortunately it gets a bit more complex if you are trying to replace characters with other characters.
Tim
Although your example is one way to do string replacement, you should note that it is not very efficient. If you don't require any complex pattern matching you should always favour a standard str_replace as it should be quicker as it doesn't need to invoke the regex engine.
Also, both str_replace and preg_replace can take arrays as their arguments so you don't need the foreach loop. You could achieve the same thing by doing.....
Code: Select all
$find = array('/\|\|/', '/\*/');
$replace = array('bad char', 'bad char');
$string = preg_replace($find, $replace, $string);
Or the quicker way...
Code: Select all
$find = array('||', '*');
$replace = array('bad char', 'bad char');
$string = str_replace($find, $replace, $string);