¿Reemplazar caracteres con palabra en PHP?

Want to replace specific letters in a string to a full word.

Estoy usando:

    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;

but that's returning:

hdhm

How do I do this? By the way, this is to replace punctuation with hex characters.

Gracias a todos.

preguntado el 09 de marzo de 12 a las 15:03

Your question is very vague - just give an example of input and desired output. -

El problema con el que te encuentras es que ord($char) isn't always a single character, which is what ord espera. -

5 Respuestas

Utilizan http://php.net/substr_replace

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

respondido 09 mar '12, 15:03

ord() expects only a SINGLE character. You're passing in hello, so ord is doing its thing only on the h:

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

So in effect your output is actually

&#104;d&#104;m

respondido 09 mar '12, 15:03

No, but you can 'explode' a string into individual characters and applies ord in a loop. - Marc B

it you want to use your same code just change $convString .= "&#".ord($char).";";

a $convString .= $char;

respondido 09 mar '12, 15:03

If you just want to replace the occurrence of a con hello within the string you pass to the function, why not use PHP's str_replace()?

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

respondido 09 mar '12, 15:03

I must assume that you don't want to have hex characters instead of punctuation but html entities. Be aware that str_replace(), when called with arrays, will run over the string for multiple times, thus replacing the ";" in "&#123;" also!

Your posted code is not useful for replacing punctuation.

use strtr() with arrays, it doesn't have the drawback of str_replace().

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

respondido 09 mar '12, 15:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.