我创建了str_inject函数,如下所示:
<?php
/* Function Calls */
// Inject one string into another at a specific point.
function str_inject($sourceStr, $injectStr, $injectPos)
{
if ($injectPos >= strlen($sourceStr)) {
trigger_error('Inject posisition is greater then the length of the source string, concating string!', E_USER_NOTICE);
return str_pad($sourceStr, $injectPos) . $injectStr;
}
return substr($sourceStr, 0, $injectPos) . $injectStr . substr($sourceStr, $injectPos);
}
/* Example Strings */
# 0123456789012345
$str1 = 'This is a string';
$str2 = ' just';
/* Example Output */
// Example 1: Proper Useage.
$str = str_inject($str1, $str2, 7);
echo $str . PHP_EOL; # echos: 'This is just a string';
// Example 2: Inproper Useage.
$str = str_inject($str1, $str2, 16);
echo $str . PHP_EOL; # echos: 'This is a string just';
// Example 3: Non Hidden, Short Hand, ECMA-48 Colours
# Make ECMA-48 of Strings.
$ecma48 = array();
for ($i = 0; $i < 8; ++$i)
{
$ecma48[$i] = "\033[3{$i}m";
}
$ecma48[] = "\033[39m"; # Reset Forground Color
$ecma48[] = "\033[0m"; # Reset All
# Setting up Varables
$str = '^1Red^8Reset Color'; # Example String
# Parse str loop
for ($i = 0, $j = 1, $l = strlen($str); $i < $l; ++$i, ++$j)
{
if ($str{$i} == '^' && is_numeric($str{$j}))
{
// Save Î Change Array Key Number & Î Len of Replace Str;
$ÎAKN = $str[$j]; # Î (Change) Array Key Number;
$ÎLen = strlen($ecma48[$ÎAKN]); # Î (Change) Array Value Len.
// Remove The Formatting
$str[$i] = NULL; # Remove ^
$str[$j] = NULL; # Remove Int.
// Place ECMA-48 Charaters into String.
$str = str_inject($str, $ecma48[$ÎAKN], $i);
// Move Str Pointers Past Î.
$i += $ÎLen;
$j += $ÎLen;
// And Increase String Size to New Length.
$l += $ÎLen - 2; # Minus two because we removed the formatting already.
}
}
# Print results.
echo $str;
?>