I am trying to implement something similar to bbcode (emoticons) from phpbb3.

The user in the place where there should be a smiley, fills the text of the form :sm_3: you need to subsequently replace it with images/smile/1.gif , I try this:

 for ($i = 0; $i < 50; $i++) { $z[] = "/:(sm_$i):/"; }; $message = preg_replace($z, '<img src="{SMILIES_PATH}/$1.gif" / >', $message); 

but I get the result.

 <img src="images/smile/:sm_3:.gif" / > 

    2 answers 2

    I do not believe.

     $text=<<<HEREDOC :sm_1: :sm_10: HEREDOC; for($i=0;$i<50;$i++){$z[]="/:(sm_$i):/";}; echo preg_replace($z,'(img src="{SMILIES_PATH}/$1.gif" / )', $text); 

    Result:

     (img src="{SMILIES_PATH}/sm_1.gif" / ) (img src="{SMILIES_PATH}/sm_10.gif" / ) 

    In general, more beautiful like this:

     preg_replace("/:sm_(.+?):/", "текст замены как в вопросе", $message); 

    Without cycles and extra arrays.

    • Thanks came up, but you just need an option with an array, because it is necessary from 1 to 50 to work ... (I noticed an error :)) - Vladimir Klykov
    • from 1 to 50: preg_replace ("/: sm_ (0? [1-9] | [1-4] [0-9] | 50): /", "replacement text as in question", $ message); - ReinRaus 2:19
    • @ReinRaus ha, very cool. He also thought about it, but somehow did not come to a conclusion. - lampa 2:21

    The first step is to understand that you want to replace " :sm_3: " with " 1 ". Now you are replacing " sm_$i ".

    Therefore:

     $message=preg_replace("/(?::sm_([0-9]+):)/", '$1', $message); 
    • What do you not believe? moder started editing at the wrong time) I gave the result I needed in the example <img src = "images / smile / 3.gif" /> - Vladimir Klykov
    • @ ToRcH565 updated post. And I don’t believe it :-) - lampa
    • Why don't you believe it?) - Vladimir Klykov
    • @ ToRcH565 I say that I don’t believe: D - lampa
    • I do not believe that the output results for the code from the question. I just copied the code from the question and it works exactly as intended. - ReinRaus