Php string char replacement library or method
Is there any library class or method to u开发者_如何转开发se not regular expressions and preg_replace()
for char replacment?
I mean something where I can get an associative array of chars to be replaced in string?
If you need to replace more than one char without clever semantics, e.g. just replace them as they are, use:
str_replace(array('+'), array('+'), $string);
// when using an associative array
str_replace(array_keys($array), array_values($array), $string);
There is specialized function for HTML entities obviously named htmlentities()
.
You can use arrays in preg_replace
too:
preg_replace(array('/quick/','/brown/'), array('slow', 'bear'), $string);
Or even associative arrays:
$array = array('/quick/' => 'slow', '/brown/' => 'bear');
preg_replace(array_keys($array), array_values($array), $string);
http://php.net/manual/en/function.strtr.php
usage:
<?php
$trans = array("h" => "e", "l" => "b", "f" => "c");
echo strtr("hi all, I said hello", $trans);
?>
Note, if i understood you, you're not looking for preg_replace or regex char replacement
edit no.1
if you need to excape this kind of data, use htmlentities
or str_replace
echo htmlentities("kkk+"); //outputs kkk+
str_replace(array('+'), array('+'), "kkk+"); //outputs kkk+
精彩评论