用PHP替换字符?

时间:2012-03-09 15:01:40

标签: php html string replace

想要将字符串中的特定字母替换为完整的字词。

我正在使用:

    function spec2hex($instr) {

   for ($i=0; $i<strlen($instr); $i++) {  

        $char = substr($instr, $i,1);  

        if ($char == "a"){
            $char = "hello";
        }

        $convString .= "&#".ord($char).";"; 

    }

    return $convString;
}

$myString = "adam";

$convertedString = spec2hex($myString);

echo $convertedString;

但那又回来了:

hdhm

我该怎么做?顺便说一下,这是用十六进制字符替换标点符号。

谢谢大家。

5 个答案:

答案 0 :(得分:0)

使用http://php.net/substr_replace

substr_replace($instr, $word, $i,1); 

答案 1 :(得分:0)

如果您只想在传递给函数的字符串中将a的出现替换为hello,为什么不使用PHP的str_replace()

function spec2hex($instr) {    
  return str_replace("a","hello",$instr);
}

答案 2 :(得分:0)

ord()只需要一个单字符。你传递的是hello,所以ord只在h上做了这件事:

php > echo ord('hello');
104
php > echo ord('h');
104

所以实际上你的输出实际上是

&#104;d&#104;m

答案 3 :(得分:0)

您要使用相同的代码,只需更改$convString .= "&#".ord($char).";";

即可

$convString .= $char;

答案 4 :(得分:0)

我必须假设您不希望使用十六进制字符而不是标点符号而不是html实体。请注意,str_replace()在使用数组调用时,将在字符串上运行多次,从而替换“;”在“&#123;”中!

您发布的代码对于替换标点符号无用。

对数组使用strtr(),它没有str_replace()的缺点。

$aReplacements = array(',' => '&#44;', '.' => '&#46;'); //todo: complete the array
$sText = strtr($sText, $aReplacements);