views:

49

answers:

4

Is there any fast (regex-based?) method to replace all smileys in a text, each by an unique corresponding identifier? For example, the first occurrence of :) should be replaced by smiley1, the :)) by smiley2 and another occurrence of :) by smiley1 again? Furthermore, the identifyier should be the same using different text for input

Any potential combination of the typical symbols (<5 chars?) such as :;-()&%}{[]D<>30_o should be recognizable.

Can this be done without a generating a large array of all combinations? In case, how?

A: 

I don't understand why you can't do:

str_replace(":))","<img src=\"smiley1.jpg\">",$STRING)
str_replace(":)","<img src=\"smiley2.jpg\">",$STRING)

etc... seems to be the most simple solution and logical

parkman47
The extendible version of this would have an array of the smiley symbols which is looped through, so there is only one actual str_replace in the code, and adding new symbols is just adding a new item to an array.
Peter Boughton
A: 

Obviously, it cannot be done by using such a str_replace. How would you fetch a ":)))" or maybe a "-.-" which is also not present in your list? Enumerating all potential smileys is a hard task, resulting in n!/(n-k)! candidates. Here, in the example provided above n=18 and k=5... Thus, I'm asking for a way to use a regex - but I don't how to replace each combination of chars which is intended to represent a smiley each time by the same text.

Idea: is it possible to use a callback function in combination with a hash?

gerd
gerd, this should be a comment on parkman47's answer. Also, edit the question to provide clear details on what you're trying to do -- I can't figure out if this is a special case, or if you're just reinventing a wheel.
Peter Boughton
+1  A: 

Are you looking for preg_replace_callback()? You can even use closures in php 5.3. I am not clear on what the objective is, so at this point this is the best I can provide, if you can clarify, then maybe I can see what I can come up with for sample code.

edit, here's an example from the PHP manual. Doesn't help in this case specifically, but if you just change the regex, the function and the string (basically everything, lol), then it will do the job:

<?php
echo preg_replace_callback('/-([a-z])/', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
Tim
A: 

Yeah, Tim! That is exactely what came into my mind when writing the last post. So the solution is

<?php
    echo preg_replace_callback("/([\)\(\[\]<>#-\.:;*+{}]{2,9})/", function ($match) {
        return " ".md5($match[1])." ";
    }, ':::-) :-)) nope (yeah) cool:) }:)');
?>

Thanks!

gerd
can you choose my answer? I just got downvotes on another one :o(
Tim