user5402695
user5402695

Reputation:

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 ?

Thanks.

Upvotes: 0

Views: 38

Answers (2)

zendyani
zendyani

Reputation: 19

You need to differentiate start and begin tag so str_replace can do the work with the exact accuracy you ask. Example:

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

echo $newString;
?> 

Upvotes: 0

coletrain
coletrain

Reputation: 2849

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

<?php
    $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!

Upvotes: 1

Related Questions