Fragmented Thought

Drupal Text Filter Skeleton

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Having to search over text can take a while, this might help speed your work up a bit. The idea is that you pass any text you like through it, and it picks up the "tags" reads the contained settings for you, and handles the replacements. This assumes you're working in PHP, but regexs and logic work everywhere of course. The syntax for these "tags" looks like [tag] or [tag|setting=value|setting2=value].

define(CUSTOM_REGEX, '/\[tag( [^]\]+ )* \] /x'); $matches = array(); $default_settings = array( 'setting' => 'value' ); $match_count = preg_match_all(CUSTOM_REGEX, $content, $matches); if($match_count > 0){ // Read in settings and replace the tags $replacements = array(); foreach($matches[0] as $key => $token){ $replacements[$key] = array( 'token' => $token ,'token_literal_regex' => string_literal_regex($token) ,'settings' => $default_settings ,'replacement' => '' ); $settings_array = explode('|', $matches[1][$key]); foreach($settings_array as $setting){ $setting_array = explode('=', $setting); if( !empty($setting_array[0]) && !empty($setting_array[1]) ){ $replacements[$key]['settings'][$setting_array[0]] = $setting_array[1]; } } $replacements[$key]['replacement'] = render_your_replacement($replacements[$key]); $content = preg_replace($replacements[$key]['token_literal_regex'], $replacements[$key]['replacement'], $content); } // Remove any remaining tags $content = preg_replace( CUSTOM_CODE_RELATED_CONTENT_REGEX, '', $content); } function string_literal_regex($string){ //All regex special chars (according to arkani at iol dot pt below): // ^ . $ | ( ) [ ] * + ? { } , $patterns = array('/\//', '/\^/', '/\./', '/\$/', '/\|/','/\(/', '/\)/', '/\[/', '/\]/', '/\*/', '/\+/','/\?/', '/\{/', '/\}/', '/\,/'); $replace = array('\/', '\^', '\.', '\$', '\|', '\(', '\)','\[', '\]', '\*', '\+', '\?', '\{', '\}', '\,'); return '/' . preg_replace($patterns,$replace, $string) . '/'; }

Code originally developed for Drupal