Image Alt Text Composer
Creates concise alt text from item title, image role, and context.
Function signature
ogComposeImageAltText(title, image_role = 'image', context = '', max_length = 125)
Categories
- File and Upload Safety
Parameters
titleHuman-facing title used for metadata, schema, or alt text.image_roleRole of the image, such as hero, thumbnail, diagram, or decorative review.contextShort surrounding context used to make composed text more precise.max_lengthMaximum preferred length for composed text.Return value
Public-safe status string returned by the function for controller branching or logging.
- success
- message
- data
Compatibility
Existing function name, slug, path, and call order preserved; advertised metadata corrected to the actual source behavior.
Minimum PHP version: 7.4
Security notes
Use caller-owned allowlists and context-specific escaping; validate file paths, routes, email tokens, cart totals, discount rules, and tax-region rules before production use.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Creates concise alt text from item title, image role, and context.
*
* Primary use case: Accessibility and SEO.
* Typical inputs: title, image role, section.
* Typical output: alt text.
*
* Implementation note: Do not stuff keywords; describe the image purpose.
*
* @param string $title Main subject title.
* @param string $image_role Image purpose such as portrait, screenshot, logo, or diagram.
* @param string $context Optional page or section context.
* @param int $max_length Maximum alt text length.
* @return array Alt text result.
*/
function ogComposeImageAltText($title, $image_role = 'image', $context = '', $max_length = 125) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$title = trim(strip_tags((string)$title));
$image_role = trim(strip_tags((string)$image_role));
$context = trim(strip_tags((string)$context));
$max_length = (int)$max_length;
if ($max_length < 40) {
$max_length = 40;
}
if (empty($title)) {
$result['message'] = 'Image title is required.';
return $result;
}
if (empty($image_role)) {
$image_role = 'image';
}
$alt = $title . ' ' . $image_role;
if (!empty($context)) {
$alt .= ' for ' . $context;
}
$alt = preg_replace('/\s+/', ' ', trim($alt));
if (strlen($alt) > $max_length) {
$alt = substr($alt, 0, $max_length);
$last_space = strrpos($alt, ' ');
if ($last_space !== false) {
$alt = substr($alt, 0, $last_space);
}
}
$result['success'] = true;
$result['message'] = 'Image alt text composed.';
$result['data'] = array('alt_text' => $alt);
return $result;
}