Replacing Placeholders in PHP
Ran across a neat little function in PHP for replacing multiple placeholder instances within a string.
Here’s an example:
$string = "<strong>##title##</strong><p>##some_text##</p>";
Here’s the PHP:
echo strtr($string,
array(
'##title##' => "The Spice...",
'##some_text##' => "Will flow!!!"
)
);
Here’s the result:
The Spice…Will flow!!!
Converting Non-English Characters in PHP
In my previous post, Removing Non-English Characters in PHP, I provided a way to remove non-english characters, but I found another neat trick to convert these characters into a close ASCII equivalent.
Here’s the code:
function unaccent($string) {
if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&') !== false) {
$string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8');
}
return $string;
}
…and here’s the source.
Removing Non-English Characters in PHP
Why would you want to do this, you say?
Well, I found out the other day a payment processor we use (Authorize.net) at the company I work at doesn’t allow for non-english characters and in return, throws a cryptic error.
Here’s the error:
E00003 - Invalid character in the given encoding. Line 15, position 54.
Here’s the trick:
$str = preg_replace('/[^\00-\255]+/u', '', $str);
…and here’s my sources and #2.