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.
If you want to be able to write shortcodes like this :
here is a more complete way, using
preg_replace_callback
andcall_user_func_array
to implement parameterized shortcodes.If this function is defined :
Then this call
Will output :
This is just something I implemented right now based on supertrue’s idea.
Any feedback is more than welcome.
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_all
andpreg_replace
on official documentation for more details.Various different approaches can be taken for this, depending on how you plan to display ect,
Take the sentence “Hello [34] world”
Create a simple function e.g replaceCode($string)
If anymore occurrences of brackets are found, recursively call the function again, passing the rest of the string to the function again.
Note: Validation may need to be done first to ensure the [ and ] are properly balanced!
My bet is PHP’s strtr function…
it’s output is
It is working fine on 5.6.
The regex, I believe, would be:
(for a 1-to-3 digit number inside double brackets.)