Strings handling with str_replace

2

I'm trying to treat a string with the function str_replace however I wanted to insert a <span> before before the treated word, as in the example below:

$entrada = array("//");
$tratamento   = array("<span class='comentario'>//</span>");
$saida = str_replace($entrada, $tratamento, $mensagem);

My question:

It is possible to do this with the function str_replace , or only with regular expressions, if it is only with ER's you would like, please give me examples.

I wanted it to return something like this:

<span class='comentario'>//</span>

Thank you!

    
asked by anonymous 09.02.2014 / 18:52

1 answer

2

Example with ER's:

$entrada = "/Olá¡ hoje é domingo/";
$saida = preg_replace('/(\/)(.*)(\/)/',"<span class='comentario'>$2<span>",$entrada);

If you want to "fetch content from // to a new line you can use: '/\/\/(.*)/' - Example

Example with explode:

$entrada = "//Olá, hoje é domingo";
$entradaArr = explode('//', $entrada);
$tratamento   = array("<span class='comentario'>", "</span>");
$saida = $tratamento[0].$entradaArr[1].$tratamento[1];
    
09.02.2014 / 19:08