Capturing [img] tags

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Serpent_Guard
Forum Newbie
Posts: 6
Joined: Mon Nov 24, 2008 2:07 pm

Capturing [img] tags

Post by Serpent_Guard »

I've been trying to get my forum to allow [ img ] tags. I want to use ereg_replace to find all strings of type '[ img ]url[ /img ]' and replace them with '< img src="url" />. I tried the command

Code: Select all

$post-text = ereg_replace('\[img\]\( \)\[/img\]', '<img src="\1" />', $post-text);
, but it just made it so my posts were empty of all text.

Or would this be much easier if I used a completely different approach?

Note: another plus would be if it could detect if 'url' has no spaces and/or ends in 'jpg', 'png', or 'gif', but right now I'm just going for the basic functionality.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Capturing [img] tags

Post by prometheuzz »

I suggest you use the preg methods instead of ereg. Also, a hyphen cannot be used inside a variable name. And lastly, you can only reference groups with a backslash (like \1) inside the regex and if you want to use it outside of the regex, as a replacement for example, then you'll have to use $1 instead.

Having said all that, try it like this:

Code: Select all

preg_replace('@\[img\](.*?)\[/img\]@i', "<img src=\"$1\" />", $post_text);
User avatar
Serpent_Guard
Forum Newbie
Posts: 6
Joined: Mon Nov 24, 2008 2:07 pm

Re: Capturing [img] tags

Post by Serpent_Guard »

Sweet, it works perfectly! Thanks!

Oh, and I realized that since I'm using bbPress's Allow-Images plugin, I don't need any kind of extension validation, since it does that for me.

Re: hyphenated variables: yeah, I was using $post-text as an example variable, but I'll keep that hyphen rule in mind so I don't waste time later tracking down errors.
Post Reply