regular expressions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

regular expressions

Post 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;
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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?
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post by Illusionist »

lol, tahts exactly what it does! Know how to fix it?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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;
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post 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!
Post Reply