You could do this with GD or ImageMagick, I will post a basic example using GD.
<?php
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'A simple text string';
// Replace path by your own font path
$font = 'tahoma.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
Now for formatting this string you can use strlen() to return the lengths of individual strings and propagate that to your function as needed. For a more stream-lined approach consider using ImageMagick because it supports TextAlignment and more.
<?php
define("LEFT", 1);
define("CENTER", 2);
define("RIGHT", 3);
$w = 400;
$h = 200;
$gradient = new Imagick();
$gradient->newPseudoImage($w, $h, "gradient:red-black");
$draw = new ImagickDraw();
$draw->setFontSize(12);
$draw->setFillColor(new ImagickPixel("#ffffff"));
$draw->setTextAlignment(LEFT);
$draw->annotation(150, 30, "Hello World1!");
$draw->setTextAlignment(CENTER);
$draw->annotation(150, 50, "Hello World2!");
$draw->setTextAlignment(RIGHT);
$draw->annotation(150, 70, "Hello World3!");
$draw->setFillColor(new ImagickPixel("#0000aa"));
$x1 = 150;
$x2 = 150;
$y1 = 0;
$y2 = 200;
$draw->rectangle($x1, $y1, $x2, $y2);
$gradient->drawImage($draw);
$gradient->setImageFormat("png");
header("Content-Type: image/png");
echo $gradient;
?>
I hope that this will help you. I can elaborate on any questions you might have.