Этот скрипт принимает текст, ищет URL, окрашивает их и создает изображение в формате png. У меня проблема с переносом слов. Поскольку я должен разбить текст на части и соединить их вместе, чтобы раскрасить ссылки, мне трудно понять, как обернуть текст. Вот сценарий и изображение результатов.
// Matches urls
function is_a_url($text) {
$isurl = preg_match("((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", $text) || preg_match("/@(\w+)/", $text) || preg_match("/#(\w+)/", $text);
return $isurl;
}
// Set defaults
$image_width = 500;
$image_height = 110;
$start_x = 5;
$start_y = 20; // initial x/y coords of text
$fontsize = 14;
$font = './font.ttf';
$angle = 0;
$im = imagecreatetruecolor($image_width, $image_height);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 51, 51, 51);
$linkcolor = imagecolorallocate($im, 51, 210, 208);
$red = imagecolorallocate($im, 200, 0, 0);
// Create the box
imagefilledrectangle($im, 0, 0, $image_width, $image_height, $red);
// Get the text
$text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem http://somelongurl.com/then-we-make-it-super-long-with-some-more/ Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum http://www.shorturl.com/ Lorem Ipsum";
//split the text on spaces so we can eval each "word"
$string_chunks = explode(' ', $text);
// Takes the split and recombine
foreach ($string_chunks as $chunk) {
//wrap based on image size
if($start_x > $image_width){
$start_x = 5;
$start_y += 20;
}
else {
$image_width = $image_width - 10;
$output .= ($counter % 15 < 1) ? '\r' : '';
}
// get coordinates of bounding box containing text
$coords = imagettfbbox($fontsize, $angle, $font, $chunk);
$end_x = $coords[0] + $coords[4] + 10;
// figure out which color to draw in
$color_to_draw = is_a_url($chunk) ? $linkcolor : $black;
// draw the text chunk
imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);
// adjust starting coordinates to the END of the just-drawn text
$start_x += $end_x;
}
// Save the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
альтернативный текст http://dl.dropbox.com/u/19973/script.png