Page 1 of 1

regular expressions

Posted: Mon Feb 16, 2004 9:49 pm
by Illusionist
ok, i read soem tuts about them and i tried this. It works when i use one tag, but if i do two tags, it wont work... anyone got any ideas?

Code: Select all

$text = "[imgg]http://forums.devnetwork.net/templates/subSilver/images/logo_phpBB.gif[/imgg]";
$Pattern = "(\[imgg\])(http://)?([^[]]+)([[]\.,-_?/&=])(\[/imgg\])";
$Replace = "<img src="http://\\3\\4"></img>";
$text = ereg_replace($Pattern, $Replace, $text);
echo $text;

Posted: Tue Feb 17, 2004 5:47 am
by Weirdan
eregs are greedy.
Perhaps your ereg returns
<img src="somethin[/imgg][imgg]something_else"></img> if you ran it on such a string:
[imgg]somethin[/imgg][imgg]something_else[/imgg]
Am I right?

Posted: Tue Feb 17, 2004 5:57 am
by Illusionist
lol, tahts exactly what it does! Know how to fix it?

Posted: Tue Feb 17, 2004 2:31 pm
by Weirdan
There are at least two ways:
  • You can switch to PERL regexps (preg_* family of functions, look up the PHP manual). They supports U modifiers for switching the 'greedyness' of pattern.
  • You can use [^[]* (inverse character class, this subregexp matches all character but opening square bracket:

    Code: Select all

    $text = "[imgg]something.jpg[/imgg][imgg]something_else.jpg[/imgg]"; 
    $Pattern = "\[imgg\](http://)?([^[]*)\[/imgg\]"; 
    $Replace = "<img src="http://\\2"></img>"; 
    $text = ereg_replace($Pattern, $Replace, $text); 
    echo $text;

Posted: Tue Feb 17, 2004 5:32 pm
by Illusionist
cool, thanks a lot. Seems more people use preg_* than ereg_* so i'm goign to start looking more into perl regular expresions!
Thanks Weirdan!