Hi,
I'm trying to use Regular Expressions for my smiley code in my CMS script, but have ran into some trouble.

The problem is, that it only replaces 1 of each type of smiley on the page (so if there are multiple of the same smilies, it wont work)

Here's the code i'm using...

$smileyfrom[] ='/(((>[^<]*)|(^[^<]*))([\s\n\r]|^))('.
	str_replace('|','\|', 
		quotemeta(
			str_replace('<', '&lt;', 
				str_replace('>', '&gt;', 
					str_replace('\/', '\\\/', $smilies[$i]
					)
				)
			)
		)
	)
.')/si';

The above is put in a loop that passes through every smiley text representation in the database for example 🙂, :-), 🙁, :-( it is then later on replaced using:

$text = preg_replace($smileyfrom, $smileyto, $text);

Any help is greatly appreciated!
Thanks in advance...

    Why dont you just use a str_replace ? [man]str_replace[/man] probably a lot quicker and a lot easier than your current attempt.

    $code = array(":)",":|",":D");
    $img = array("path/to/smile","path/to/confused","path/to/big_grin");
    $string = str_replace($code,$img,$string);
    

    As you can see str_replace can accept arrays.

      I've tried the str_replace method, but you get errors when inside of HTML, for example..

      <a href="mailto:p.....">

      would replace the :p with a smiley and throw up errors in the HTML code...

        This is what I use to make string replacement outside html tags.

        // function called by preg_replace_callback
        function mon_rplc($capture){ 
          $smiley = array(':)',':|',':D',':p'); 
          $icon = array('/smile/','/confused/','/big_grin/','nyah'); 
          return str_replace($smiley, $icon, $capture[1]).$capture[2];
        } 
        
        // sample text
        $txt = '<div id=":)">This <---- text :) outside tags<a href="mailto:p..."> mail me :p </a>whatever <a text href="http://text.com">text</a> here</div> and final text :D';
        
        // separates what is inside and outside html tags
        $out = preg_replace_callback('#(?:(?<=>)|^)((?:(?!<[/a-z]).)*)([^>$]*>|$)#is', "mon_rplc", $txt);
        
        // display result 
        echo htmlentities($out);

        I took me a while to make that regex. It's certainly not perfect but it works. Hope this helps.

          thanks a lot,
          that code works perfectly!

            Write a Reply...