Replace ShortCode using PHP

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here we have a data.html file with two shortcodes marked by square brackets: [myimage.jpg] and [myimage2.jpg] …

data file with shortcode

data file with shortcode

I want to write PHP code to search and replace with these…

<a href=”myimage.jpg”><img src=”myimage.jpg”></a>

<a href=”myimage2.jpg”><img src=”myimage2.jpg”></a>

Shortcodes are like shortcuts that saves me from typing in those long HTML tags.   WordPress uses shortcode for certain widgets replacements.

Here is the PHP that I use …

php to process shortcodes

php to process shortcodes

I read the file using PHP’s file_get_contents() into a string $inFile and $outText.

Use preg_match_all on $outText with regular expression “/\[(.*?)\]” to find all shortcodes within brackets.  The preg_match_all returns all matches in two arrays.  The first array (in our case $matches[0]) is an array of matches with the brackets included.  The second array ($mathes[1]) is an array of matches with just the match content (excluding the bracket symbols).

We loop through this second array for all the matched contents.  For each matched content (in our case “$match”), we build up a new string in $newValue.

We use str_replace to replace our match with our new string.

And output back to same file using file_put_contents.