Here's a generic solution for your problem, and ones similar to it:
// function str_replace_conditional($str, $arr, $srch, $repl, $delete = true)
// Replaces $srch with $repl in $str,
// unless $srch is immediately preceded by any string in $arr.
// If $delete == true, $srch preceded by a value in $arr will be deleted,
// else $srch will be left in place.
// All strings may be any length.
// Returns processed $str.
function str_replace_conditional($str, $arr, $srch, $repl, $delete = true)
{
$offset = 0;
while (($pos = strpos($str, $srch, $offset)) !== false) {
$replaced = false;
foreach ($arr as $each) {
$len = strlen($each);
if (substr($str, $pos - $len, $len) == $each) {
if ($delete) {
$str = substr_replace($str, '', $pos, strlen($srch));
}
$replaced = true;
break;
}
}
if (!$replaced) {
$str = substr_replace($str, $repl, $pos, strlen($srch));
}
$offset = $pos + 1;
}
return $str;
}
Tested, but not strenuously.
Not meant to compete with any regular expression solution.
Demo script:
$string = "\nadmin@\nexample.com \n mail@example.\ncom &\nhello\n";
$array = array('@', '&');
$search = "\n";
$replace = '<br />';
$new_string = str_replace_conditional($string, $array, $search, $replace);
echo '<pre>' . htmlentities($string) . '</pre><br />';
echo $string . '<br />';
echo '____________________' . '<br />';
echo '<pre>' . htmlentities($new_string) . '</pre><br />';
echo $new_string . '<br />';
Output:
admin@
example.com
mail@example.
com &
hello
admin@ example.com mail@example. com & hello
____________________
<br />admin@example.com <br /> mail@example.<br />com &hello<br />
[email]admin@example.com[/email]
mail@example.
com &hello