您不仅需要识别颜色,还需要对齐字符串。这不是自动的,因为它在 HTML 中。
我会首先将字符串拆分为其组成部分:
// Split the text using hex colors as strings:
$hex = '[0-9a-fA-F]'; // Capital hex should be supported
$colorex = "(#{$hex}{$hex}{$hex}{$hex}{$hex}{$hex})";
// or also $colorex = "(#{$hex}{6})";
$parts = preg_split ("/{$colorex}/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
// Then you would iterate through the parts:
$color = imageColorAllocate($gd, 0, 0, 0); // Default is black
foreach($parts as $part)
{
// Scan the hex value
if (preg_match("/^{$colorex}\$/", $part, $gregs))
{
sscanf($gregs[1], "#%02x%02x%02x", &$r, &$g, &$b);
$color = imageColorAllocate($gd, $r, $g, $b);
continue;
}
// IMPROVEMENT: if count(explode("\n", $part)) > 1, $y += $height, $x = 0
// to indicate "go to next line". So this would appear on two lines:
// #012345Hel#ff7700lo,
// #443212World
// Next section will be repeated for each item
// in the exploded string.
//! $subparts = explode("\n", $part);
//! foreach($subparts as $part)
//! { // We have overwritten $part
// Here $part is printed as string at position $x, $y
// Ask GD to calculate string width
// with http://php.net/manual/en/function.imagettfbbox.php
// Calculations with $angle != 0 is a bit more difficult, entails trigonometric
// evaluation of $w and $h.
$bbox = imagettfbbox ($size, $angle, $fontfile, $part);
$w = $bbox[4] - $bbox[0]; // 0,1 is lower left corner
$h = $bbox[5] - $bbox[1]; // 4,5 is upper right
imagettftext ($gd, $size, $angle, $x, $y, $color, $fontfile, $part);
// Increment $x position by $w
$x += $w;
//! if (count($subparts) > 1)
//! {
//! $x = 0; $y += $h;
//! }
//! }
}