Question: At the moment I have:

```
//replace common characters
$search = array('&', '£', '$'); 
$replace = array('&amp;', '&pound;', '&dollar;'); 
$html= str_replace($search, $replace, $html);

```

The problem with this code is that if the & has been already converted it will try to convert it again. How would I make sure this doesn't happen?

Answer: 
I would use the built in functions that PHP has to escape HTML characters:

* [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php)
* [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php)

Rather than rolling my own as it is much easier. `htmlentities()` and `htmlspecialchars()` explicitly handle this with the `double_encode` parameter:

> 
> When double\_encode is turned off PHP will not encode existing html
>  entities. The default is to convert everything.
> 
> 
>
i give an example but it will work if you have the latter like `' & '` then hope this will work for you:

```
$str = 'India & Aust &amp; New ';
$regex = '/(\s\&\s)/i';
$replace = ' &amp; ';

if(preg_match($regex, $str)){
    $new_str = preg_replace($regex, $replace, $str );

    echo '<pre>';
    echo htmlspecialchars($new_str, ENT_QUOTES);
    echo '</pre>';
}
else{
    echo 'Not matched!';
}

```

but remember this will work if you have space on both sides of an ampersand or whatever you want. Otherwise follow the @Treffynnon Answer..