开发者

Php string char replacement library or method

开发者 https://www.devze.com 2023-04-02 07:26 出处:网络
Is there any library class or method to u开发者_如何转开发se not regular expressions and preg_replace() for char replacment?

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&#43;
str_replace(array('+'), array('&#43;'), "kkk+"); //outputs kkk&#43;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号