...

View Full Version : usage of preg_replace



SDP2006
11-29-2003, 08:14 PM
how might I use preg_replace to replace a :) with a source to an image? Can someone show an example with more than one smiley combination?

Thanks

Nightfire
11-29-2003, 09:25 PM
Look at example 2:

http://uk.php.net/preg_replace

SDP2006
11-30-2003, 03:22 AM
**slaps forehead**
Thanks!

SDP2006
11-30-2003, 03:55 PM
<?php
$string = "Thanks Nightfire! :D";
$patterns[0] = "/:D/";
$replacements[0] = "<img src=\"grin.gif\">";
print preg_replace($patterns, $replacements, $string);
?>

btw, I did check the manual, I just must have overlooked that example

Nightfire
11-30-2003, 04:03 PM
No problem ;)

SDP2006
11-30-2003, 08:12 PM
Bah, now I get an error


$string = strip_tags($_POST['comments']);
$text[0] = "/:|/";
$image[0] = "<img src=\"emoticons/longface.gif\">";
$final = preg_replace($text, $image, $string); // line 24
print $final;

Error is
Warning: Compilation failed: missing ) at offset 2 in /home2/gudioco/public_html/implex/GuestBook/add.php on line 24

SDP2006
12-01-2003, 02:05 AM
Anyone?

Nightfire
12-01-2003, 02:12 AM
Not sure, but try doing the preg_replace() without any spaces in



$final = preg_replace($text,$image,$string);


or try



$text[0] = "/:\\|/";


Can only be something stupid

SDP2006
12-01-2003, 02:40 AM
I really don't know, but I fixed it. Here is the code that works
$string = $_POST['comments'];
$nohtml = strip_tags($string);

$patterns[0] = "/:D/";
$patterns[1] = "/:happy:/";
$patterns[2] = "/:P/";

$replacements[2] = "<img src=\"longface.gif\">";
$replacements[1] = "<img src=\"emoticons/longface.gif\">";
$replacements[0] = "<img src=\"longface.gif\">";

$final = preg_replace($patterns, $replacements, $nohtml);
print $final;

Hmmm. o well, it works

ReadMe.txt
12-02-2003, 12:27 AM
it was the :| that was breaking it, since | is part of the regexp syntax, u need to use :/| for the :| smiley, altho i think str_replace would be fine for this usage.

nicklim
12-02-2003, 05:06 AM
instead of preg, why don't you use str_replace instead... it's less sensitive.. and you don't need all those fancy expression replacements...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum