Page 1 of 1

Capturing [img] tags

Posted: Tue Dec 09, 2008 11:52 am
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.

Re: Capturing [img] tags

Posted: Tue Dec 09, 2008 12:04 pm
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);

Re: Capturing [img] tags

Posted: Tue Dec 09, 2008 12:34 pm
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.