Skip to content

Instantly share code, notes, and snippets.

@matb33
Created September 20, 2011 14:57
Show Gist options
  • Save matb33/1229317 to your computer and use it in GitHub Desktop.
Save matb33/1229317 to your computer and use it in GitHub Desktop.
Inline variable parsing function with multibyte support
<?php
// parseInlineVariables takes a multibyte string "stringToParse" and parses for $variable style
// variables to swap with the value found in the "variables" associative array. It also supports
// better matching with curly braces surrounding the variable, such as {$variable}. Spaces
// within the curly braces are OK: { $variable } works too.
// Adapt this function to your particular framework (put it in a class, keep it global, etc)
function parseInlineVariables( $stringToParse, Array $variables )
{
do
{
mb_ereg_search_init( $stringToParse, '({[ ]*\$[A-Za-z0-9-_]+[ ]*}|\$[A-Za-z0-9-_]+)' );
if( ( $pos = mb_ereg_search_pos() ) !== false )
{
$offset = $pos[ 0 ];
$length = $pos[ 1 ];
$match = mb_substr( $stringToParse, $offset, $length );
$key = trim( $match, '${} ' );
$before = mb_substr( $stringToParse, 0, $offset );
$after = mb_substr( $stringToParse, $offset + $length );
$value = isset( $variables[ $key ] ) ? ( string )$variables[ $key ] : "";
$stringToParse = $before . $value . $after;
}
}
while( $pos );
return $stringToParse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment