PacPac PacPac - 11 months ago 27
PHP Question

Replace special string part in PHP

I need to transform this string:

Hello, i'm **super** and **tall**.

to this one:

Hello, i'm <big>super</big> and <big>tall</big>.

So I use this:

$string = "Hello, i'm **super** and **tall**.";
$old = array("**", "**");
$new = array("<big>", "</big>");
$newString = str_replace($old, $new, $string);

But it don't work.

Could you please help me ?



You can definitely clean this up a bit but, this should get the job done.

    $string = "Hello, i'm **super** and **tall**.";
    $pattern = '/\*{2}/';
    $replacement = '<big>';
    $result =  preg_replace($pattern, $replacement, $string);

    $pattern2 = '/\b(<big>)/';
    $replacement = '</big>';
    echo preg_replace($pattern2, $replacement, $result);

I am using regex oppose to an array but, the first regex /\*{2}/ look for 2 **. If if finds the 2 ** it will replace them with <big>. The second regex \b(<big>) will then look for all odd occurrences (or ending tags) and will replace it with the appropriate ending html tag. Hope this helps!