开发者

Replace a tag in a MySQL text field with an image

Brand new to PHP and MySQL and have been trying to figure out how to replace a tag (i.e. [image:1]) in a blog post's t开发者_StackOverflowext field with the correct image. I have the ability now (thanks to some pointers in the right direction) to place the correct pictures with the correct posts, but I would like to actually drop them into the text based on where I put the tag in the post itself. For instance, right now I can echo the picture before I echo the $row['post'] itself, but I can't figure out how to program the php to actually look through the $row['post'], find the [image:1], echo the picture with that id there, and then continue echoing the rest of the post. Does that make sense?


If you have the image tag in a variable $image_tag, and if your post body is contained in $row['post'], your logic should look something like:

 $body_text = str_replace ( "[image:1]", $image_tag, $row['post']);
 echo $body_text;

So basically, instead of first dumping the image and then the body text, first replace your image placeholder with the corresponding image tag before writing it out.


If your "tag" is a known string and will never change, then PHP's str_replace() function will probably be sufficient for you:

$output = str_replace( "[input:1]", $replacement_string, $original_string);

If your tag string can vary -- say you want to have [image:1] but also [image:anything-else], then you may find preg_replace() to be a more useful function. preg_replace() allows you to replace strings using more advanced pattern matching (regex):

$output = preg_replace( "/\[input:(.+)\]/", '<img src="image_number_$1">', $original_string);

In this example, the replacement string includes a reference to the image number in the original tag -- ie (.+) is mapped to $1.

Regex is a whole discussion in itself, so if you don't know much about it, I recommend reading up -- it's very powerful, but can be quite cryptic (the above is a relatively simple example!).

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜