I'm trying to produce a Wordpress shortcode-style feature in PHP to exchange shortcodes like "[[133]]" with images. Essentially, I've got a MySQL table of image Web addresses/game titles/subtitles with IDs 1-150, and I wish to have the ability to dynamically place them in to the text of my pages with shortcodes such as this:

Blabla bla bla bla bla. [[5]] Also, bla bla bla bla bla [[27]] Hey, and bla bla bla! [[129]]

So, Among the finest to seize the ID as $id, after which feed it to some MySQL query like mysql_query("Choose title,subtitle,url FROM images WHERE id = $id") after which replace the "[[id]]" using the img/title/subtitle. I must have the ability to do that multiple occasions on a single page.

I understand this needs to involve regex plus some mixture of preg_match, preg_replace, strstr, strpos, substr... but I'm not sure how to start and which functions I ought to be utilising to complete which things. Are you able to recommend a method? I do not require the code itself—just understanding what for which parts could be very useful.

The regex, In my opinion, could be:

/[[[1-9]]]/g

(for any 1-to-3 digit number inside double brackets.)

Having a function getimage($id) that does the MySQL query and formats the alternative text, this almost does all you need:

$text = "Blabla [[5]] and [[111]] bla bla bla [[27]] and bla bla bla! [[129]]";

$zpreg = preg_match_all('#\[\[(\d{1,3})\]\]#', $text, $matches );

var_dump( $matches[1] );  

$newtext = preg_replace('#\[\[(\d{1,3})\]\]#', getimage($matches[1][?????]), $text);

echo $newtext;

I simply need to evaluate which to place inside getimage() (where ????? is) that can make it make the right image for the best [[id]].

Many different approaches could be taken with this, for the way you intend to show ect,

Go ahead and take sentence "Hello [34] world"

Produce a simple function e.g replaceCode($string)

function replaceCode($string){

    $pos = strpos($string, '['); // Find the first occurrence of the bracket

    if($pos != false){

          // If everything is ok take the next 2 numbers from it

          // Check for a close bracket & remove ]

          // call another function to replace the number with the image text

    }




}

If any longer occurrences of brackets are located, recursively call the function again, passing the relaxation from the string towards the function again.

Note: Validation might need to be achieved first to guarantee the [ and ] are correctly balanced!