【问题标题】:Replace characters with word in PHP?用PHP中的单词替换字符?
【发布时间】:2012-03-09 15:01:39
【问题描述】:

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

我正在使用:

    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

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

谢谢大家。

【问题讨论】:

  • 你的问题很模糊——只举一个输入和期望输出的例子。
  • 您遇到的问题是ord($char) 并不总是一个字符,而这正是ord 所期望的。

标签: php html string replace


【解决方案1】:

使用http://php.net/substr_replace

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

【讨论】:

    【解决方案2】:

    ord() 只需要一个字符。你传入hello,所以 ord 只在h 上做它的事情:

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

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

    &#104;d&#104;m
    

    【讨论】:

    • 否,但您可以将字符串“分解”为单个字符并在循环中应用 ord。
    【解决方案3】:

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

    $convString .= $char;

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        您发布的代码不能用于替换标点符号。

        将 strtr() 与数组一起使用,它没有 str_replace() 的缺点。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-29
          • 1970-01-01
          • 1970-01-01
          • 2015-07-03
          相关资源
          最近更新 更多