String-based...okay.... let's see... This is probably faster than copying stuff across one character at a time. (Incidentally, onno182's loop will fail on your example 4; it will also throw an Uninitialised String Offset notice every time you use it).
The biggest thing to keep an eye on is that in C arrays (and strings) are identified by pointers into memory, while in PHP they're first-class citizens. So mapping pointer arithmetic can be tricky. In particular, pointers into pre-existing strings are offset relative to the start of the string, not to the start of memory (so the first character of a string is always at position 0). So it seems an extra parameter to memcpy are needed to fully specify the destination (one parameter to identify the string, one to identify its offset).
function memset(&$buffer, $c, $num)
{
$buffer = str_repeat($c, $num);
}
function memcpy(&$dest, $offset, $src, $num=-1)
{
// Often, we want to copy the entire $src. This saves us having to call
// strlen($src) before calling memcpy() in that situation
// memcpy($foo, 0, $bar) will copy ALL of $bar into the initial
// part of $foo.
if($num==-1) $num=strlen($src);
$dest = substr($dest, 0, $offset).substr($src, 0, $num).substr($dest, $offset+$num);
}
The nice thing about this memcpy is that there is no danger of running off the end of the $dest buffer - the string just gets longer.
1.) initialize the entire line (record) to spaces
2.) insert characters 'foo' starting at position 4
3.) insert characters 'foofoo' starting at position 21
4.) insert characters '360' starting at position 29
5.) insert characters '\r\n' starting at position 200
6.) write the line to a file
$foos = 'foofoo';
memset($record, ' ', 200);
memcpy($record, 4, $foos, 3);
memcpy($record, 14, $foo); // Doubles as an illustration of the default argument.
memcpy($record, 29, '360');
memcpy($record, 200, "\r\n"); // Look! No buffer overrun!