Improving a shortcode replacement routine PHP and regex I am using wordpress to allow a client to enter a curriculum vitae and have it output the correct and consistent html formatting:



So I have a plain text box custom field and am having them enter in the content in the following way:

[section "Solo Exhibitions"]
[year 2011]

Inner Space
January 11

Peter Pan
February 11

[section "Group Shows"]
[year 2009]

Group Show
January 09

Big Group Show
February 09


So on and so forth. I wrote the following to parse that text field and output the correct HTML formatting, but I think it is pretty brute force-- not very much finesse.

$cv = get('cv_text');
$cv = strip_tags($cv);

// Remove empty line breaks
$cv = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", $cv);

// Explode line breaks
$cv = explode("\n", $cv);

$i = 0;

foreach($cv as $line) {
    if( preg_match('/\[section \"(.*)\"\]/', $line) ) {
        echo preg_replace('/\[section \"(.*)\"\]/', '&lt;h2&gt;$1&lt;/h2&gt;', $line);
    } elseif( preg_match('/\[year (\d*)\]/', $line) ) {
        echo preg_replace('/\[year (\d*)\]/', '&lt;h3&gt;$1&lt;/h3&gt;', $line);
    } else {
        // Count every two lines and wrap in a &lt;p&gt; tag
        if($i === 1) {
            echo '&lt;em&gt;'.$line.'&lt;/em&gt;&lt;/p&gt;';
            $i = 0;
            continue;
        } else {
            echo '&lt;p&gt;'.$line.'&lt;/br&gt;
            ';
            $i++;
        }
    }
}


Can anyone recommend a way to improve my present code or present a better approach?

Thanks!
Why are you having them write that all in one box? And with custom tags no less!

I'd just create a form with each of these fields in it (section, year, event), with a JS "add" button below the event to add additional events to the DOM. Then if you want to give them the option of adding multiple sections at a time, then you can add another "add" button below the section that will duplicate an unmodified version of the original form so that they can do it all over again.

This is much better than having your client learn your custom tags for your program. And if you were to continue this route you'd end up recreating BB code, which there are plenty enough out there that you'd be better off downloading one instead. Not to mention that the above method is also easier on you. No need to create a custom parser at that point, just extract the proper keys from the POST data. I'm not going to put the code here, simply because a simple google search will find what you're looking for easier and faster than I could write it all here.

As for improvement to your code, I'd steer clear of Regex, but that's just me. I wasn't born on whatever planet that language came from.