开发者

replacing certain images with certain words

开发者 https://www.devze.com 2022-12-14 18:39 出处:网络
i want to chan开发者_如何学JAVAge the word :)) to a smily img before displaying it from database with php how can i do thatA solution would be to use the str_replace function.

i want to chan开发者_如何学JAVAge the word :)) to a smily img before displaying it from database with php how can i do that


A solution would be to use the str_replace function.

For instance (Using ":-)", which I like more than your ":))" -- only a matter of taste ^^ Up to you to use the "right one") :

$str = "This is a sentence with a smiley :-)";

$new_str = str_replace(
    array(
        ':-)', 
    ), 
    array(
        '<img src="smiley.png" alt=":-)" />'
    ),
    $str
);

echo $new_str;

Will get you this output :

This is a sentence with a smiley <img src="smiley.png" alt=":-)" />

i.e. the smiley has been replaced with an image.


Note that I used an array for the first and second parameter, when calling str_replace : if you have other smileys, you can just add them to those two arrays (the first array being for the "searched" string, and the second for the "replacement").

(What I mean is : no need to call str_replace several time : one time, using arrays, should be enough for several replacements)


And, as a sidenote : I used the original "text" of the smiley for the alt attribute of the img tag : this way, if the image cannot be displayed, the browser will display the textual version of the smiley -- which is better than nothing.


You could use something like:

str_replace(':))', '<img src="path to your image" title="image title" />', $string);

If you want to replace multiple 'smileys', use arrays:

$find = array(
            ':)',
            ':('
        );
$replace = array(
               '<img src="path to happy image" title="" />', 
               '<img src="path to sad image" title="" />');
           );
str_replace($find, $replace, $string);


You can use something like the following. Create a new replacement for each image you've got.

$message = str_replace(":)", "<img src='happy.png' alt=':)'/>", $message);
$message = str_replace(":(", "<img src='unhappy.png' alt=':('/>", $message);

This will turn $message "I'm happy :)" into "I'm happy <img src='happy.png' alt=':)'/>". The alt tag reveals the original smiley when users don't see images.

0

精彩评论

暂无评论...
验证码 换一张
取 消