I am trying to create a WordPress shortcode-style feature in PHP to replace shortcodes like “[[133]]” with images. Basically, I have a MySQL table of image URLs/titles/subtitles with IDs 1-150, and I want to be able to dynamically insert them into the text of my pages with shortcodes like this:
Blabla bla bla bla bla. [[5]] Also, bla bla bla bla bla [[27]]
Hey, and bla bla bla! [[129]]
So, I just want to grab the ID as $id, and then feed it to a MySQL query like
mysql_query(“SELECT title,subtitle,url FROM images WHERE id = $id”)
and then replace the “[[id]]” with the img/title/subtitle. I would like to be able to do this multiple times on the same page.
I know this has to involve regex and some combination of preg_match, preg_replace, strstr, strpos, substr… but I don’t know where to start and which functions I should be using to do which things. Can you recommend a strategy? I don’t need the code itself—just knowing what to use for which parts would be extremely helpful.
With a function
getimage($id)that does the MySQL query and formats the replacement text, this almost does everything you need:I just need to figure out what to put inside
getimage()(where ????? is) that will make it put in the right image for the right[[id]].Refer
preg_match_allandpreg_replaceon official documentation for more details.