pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

具有像素尺寸的 PHP 自動換行

PHP word wrap with pixel dimensions(具有像素尺寸的 PHP 自動換行)
本文介紹了具有像素尺寸的 PHP 自動換行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我正在尋找一種使用 PHP 將文本包裝到特定寬度的框中的方法.我收到了動態文本字符串和可變字體大小.

我找到了一個很好的方法,可以從這個線程中按照我想要的方式剪切文本:PHP 中長字的智能自動換行?>

使用此代碼塊:

function smart_wordwrap($string, $width = 10, $break = "
") {//在行長度上拆分問題詞$pattern = sprintf('/([^ ]{%d,})/', $width);$輸出 = '';$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);foreach ($words as $word) {if (false !== strpos($word, ' ')) {//正常行為,重建字符串$output .= $word;} 別的 {//計算當前行有多少個字符$wrapped = expand($break, wordwrap($output, $width, $break));$count = $width - (strlen(end($wrapped)) % $width);//填充當前行并添加一個中斷$output .= substr($word, 0, $count) .$break;//包裝問題單詞中的所有剩余字符$output .= wordwrap(substr($word, $count), $width, $break, true);}}//包裝最終輸出return wordwrap($output, $width, $break);

}

這很好用,但我需要找到一種方法將設置的像素尺寸(約束框)和字體大小輸入到上面.上面的函數使用了字符數 - 如果字體大小很明顯,字符數需要更大,反之亦然.

如果我有以下變量,我可以這樣做嗎?

$boxWidth = 200(px);$text = (動態字符串);$font = '自定義字體.ttf'$fontSize = (動態大小);

我正在考慮對自動換行功能進行另一個循環.或者也許有一種方法可以編輯爆炸",因為我不完全確定該功能是如何工作的.

解決方案

As @Mark Ba??ker 建議 我已經使用 imagettfbbox()

  • 可以在此處
  • 找到帶有輔助函數的完整代碼片段
  • 我正在發布相關代碼以供參考

//幫助在圖像上渲染文本的實用函數

//返回渲染文本的預期寬度(以像素為單位)公共靜態函數 getWidthPixels(string $text, string $font, int $font_size): int {//https://www.php.net/manual/en/function.imageftbbox.php#refsect1-function.imageftbbox-returnvalues$bbox = imageftbbox($font_size, 0, $font, " " . $text);返回 $bbox[2] - $bbox[0];}//返回一段文本的包裝格式(帶換行符)(打算在圖像上呈現)//使用渲染的文本邊界框的寬度公共靜態函數 wrapTextByPixels(字符串 $text,int $line_max_pixels,整數 $font_size,字符串 $font): 細繩 {$words = expand(' ', $text);//將文本標記為單詞$行 = [];//Array[Array[string]]: 存儲單詞行的數組$crr_line_idx = 0;//(從零開始)當前行的索引,在其中添加單詞$crr_line_pixels = 0;//當前行的寬度(在其中添加單詞)以像素為單位foreach ($words as $word) {//確定當前行的新寬度(以像素為單位)如果當前單詞被添加到它(包括空格)$crr_line_new_pixels = $crr_line_pixels + ImageTextRenderUtils::getWidthPixels(' ' . $word, $font, $font_size);//確定當前單詞的寬度(以像素為單位)$crr_word_pixels = ImageTextRenderUtils::getWidthPixels($word, $font, $font_size);如果($crr_word_pixels > $line_max_pixels){//如果當前單詞本身太長而無法放入一行//那么我們別無選擇:它仍然必須只放在單行中如果($crr_line_pixels == 0){//但只有當前行為空時才放入當前行$lines[$crr_line_idx] = array($w??ord);$crr_line_idx++;} 別的 {//否則如果當前行非空,則將超長的單詞放入換行符$crr_line_idx++;$lines[$crr_line_idx] = array($w??ord);$crr_line_idx++;$crr_line_pixels = 0;}} else if ($crr_line_new_pixels > $line_max_pixels) {//否則如果當前行的新寬度(包括當前單詞和空格)//超過最大允許寬度,則強制當前單詞換行$crr_line_idx++;$lines[$crr_line_idx] = array($w??ord);$crr_line_pixels = $crr_word_pixels;} 別的 {//else 如果當前單詞(包括空格)可以放入當前行,則將其放在那里$lines[$crr_line_idx][] = $word;$crr_line_pixels = $crr_line_new_pixels;}}//上面的foreach循環結束后,$lines二維數組Array[Array[string]]//將包含分隔成行的單詞以保留 $line_max_pixels//現在我們只需要將行(字串數組)拼接成一個連續的文本片段$concatenated_string = array_reduce($行,靜態函數(字符串 $wrapped_text,數組 $crr_line):字符串 {返回 $wrapped_text .PHP_EOL .內爆(' ', $crr_line);},'');//上面將行拼接成單段文本的過程會不經意間//在開頭添加一個額外的換行符 '
';所以我們必須刪除它return StringUtils::removeFirstOccurrence($concatenated_string, "
");}

I'm looking for a way to wrap text into a box of specific width using PHP. I have dynamic text strings coming in, and variable font sizes.

I found a great way to cut the text up the way I want it from this thread: Smarter word-wrap in PHP for long words?

Using this block of code:

function smart_wordwrap($string, $width = 10, $break = "
") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

foreach ($words as $word) {
    if (false !== strpos($word, ' ')) {
        // normal behaviour, rebuild the string
        $output .= $word;
    } else {
        // work out how many characters would be on the current line
        $wrapped = explode($break, wordwrap($output, $width, $break));
        $count = $width - (strlen(end($wrapped)) % $width);

        // fill the current line and add a break
        $output .= substr($word, 0, $count) . $break;

        // wrap any remaining characters from the problem word
        $output .= wordwrap(substr($word, $count), $width, $break, true);
    }
}

// wrap the final output
return wordwrap($output, $width, $break);

}

This works great, but I need to find a way to feed a set pixel dimension (the constraining box), and font size into the above. The above function is using a character count - and if the font-size is very small obviously the character count needs to be larger and vice versa.

Is there anyway I could do this if I have the following variables?

$boxWidth = 200(px);
$text = (dynamic string);
$font = 'customfont.ttf'
$fontSize = (dynamic size);

I was thinking another loop to the word wrap function. Or maybe there's a way to edit the "explode" as I'm not entirely sure how that function works.

解決方案

As suggested by @Mark Baker I have implemented this behaviour using imagettfbbox()

  • Complete code-snippet with helper functions can be found here
  • I'm posting the relevant bits of code for reference

// utility functions to help text rendering on image

// Returns expected width of rendered text in pixels
public static function getWidthPixels(string $text, string $font, int $font_size): int {
    // https://www.php.net/manual/en/function.imageftbbox.php#refsect1-function.imageftbbox-returnvalues
    $bbox = imageftbbox($font_size, 0, $font, " " . $text);
    return $bbox[2] - $bbox[0];
}

// Returns wrapped format (with newlines) of a piece of text (meant to be rendered on an image)
// using the width of rendered bounding box of text
public static function wrapTextByPixels(
    string $text,
    int $line_max_pixels,
    int $font_size,
    string $font
): string {
    $words = explode(' ', $text);   // tokenize the text into words
    $lines = [];                             // Array[Array[string]]: array to store lines of words
    $crr_line_idx = 0;                       // (zero-based) index of current lines in which words are being added
    $crr_line_pixels = 0;                    // width of current line (in which words are being added) in pixels

    foreach ($words as $word) {
        // determine the new width of current line (in pixels) if the current word is added to it (including space)
        $crr_line_new_pixels = $crr_line_pixels + ImageTextRenderUtils::getWidthPixels(' ' . $word, $font, $font_size);
        // determine the width of current word in pixels
        $crr_word_pixels = ImageTextRenderUtils::getWidthPixels($word, $font, $font_size);


        if ($crr_word_pixels > $line_max_pixels) {
            // if the current word itself is too long to fit in single line
            // then we have no option: it must still be put in oneline only
            if ($crr_line_pixels == 0) {
                // but it is put into current line only if current line is empty
                $lines[$crr_line_idx] = array($word);
                $crr_line_idx++;
            } else {
                // otherwise if current line is non-empty, then the extra long word is put into a newline
                $crr_line_idx++;
                $lines[$crr_line_idx] = array($word);
                $crr_line_idx++;
                $crr_line_pixels = 0;
            }
        } else if ($crr_line_new_pixels > $line_max_pixels) {
            // otherwise if new width of current line (including current word and space)
            // exceeds the maximum permissible width, then force the current word into newline
            $crr_line_idx++;
            $lines[$crr_line_idx] = array($word);
            $crr_line_pixels = $crr_word_pixels;
        } else {
            // else if the current word (including space) can fit in the current line, then put it there
            $lines[$crr_line_idx][] = $word;
            $crr_line_pixels = $crr_line_new_pixels;
        }
    }

    // after the above foreach loop terminates, the $lines 2-d array Array[Array[string]]
    // would contain words segregated into lines to preserve the $line_max_pixels

    // now we just need to stitch together lines (array of word strings) into a single continuous piece of text with
    $concatenated_string = array_reduce(
        $lines,
        static function (string $wrapped_text, array $crr_line): string {
            return $wrapped_text . PHP_EOL . implode(' ', $crr_line);
        },
        ''
    );

    // the above process of concatenating lines into single piece of text will inadvertently
    // add an extra newline '
' character in the beginning; so we must remove that
    return StringUtils::removeFirstOccurrence($concatenated_string, "
");
}

這篇關于具有像素尺寸的 PHP 自動換行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Add programmatically a downloadable file to Woocommerce products(以編程方式將可下載文件添加到 Woocommerce 產品)
Get today#39;s total orders count for each product in Woocommerce(獲取今天 Woocommerce 中每種產品的總訂單數)
Add Custom registration fields in WooCommerce and phone field validation issue(在 WooCommerce 和電話字段驗證問題中添加自定義注冊字段)
Add a select field that will change price in Woocommerce simple products(在 Woocommerce 簡單產品中添加一個將更改價格的選擇字段)
Add custom columns to admin products list in WooCommerce 3(在 WooCommerce 3 中將自定義列添加到管理產品列表)
Customizing checkout quot;Place Orderquot; button output html(自定義結帳“下訂單按鈕輸出html)
主站蜘蛛池模板: 油罐车_加油机_加油卷盘_加油机卷盘_罐车人孔盖_各类球阀_海底阀等车用配件厂家-湖北华特专用设备有限公司 | 展厅设计-展馆设计-专业企业展厅展馆设计公司-昆明华文创意 | 企典软件一站式企业管理平台,可私有、本地化部署!在线CRM客户关系管理系统|移动办公OA管理系统|HR人事管理系统|人力 | 济南侦探调查-济南调查取证-山东私家侦探-山东白豹调查咨询公司 密集架|电动密集架|移动密集架|黑龙江档案密集架-大量现货厂家销售 | 压滤机滤板_厢式_隔膜_板框压滤机滤板厂家价格型号材质-大凯环保 | 铸铝门厂家,别墅大门庭院大门,别墅铸铝门铜门[十大品牌厂家]军强门业 | 生产自动包装秤_颗粒包装秤_肥料包装秤等包装机械-郑州鑫晟重工科技有限公司 | 中高频感应加热设备|高频淬火设备|超音频感应加热电源|不锈钢管光亮退火机|真空管烤消设备 - 郑州蓝硕工业炉设备有限公司 | 玉米深加工设备|玉米加工机械|玉米加工设备|玉米深加工机械-河南成立粮油机械有限公司 | 有机废气处理-rto焚烧炉-催化燃烧设备-VOC冷凝回收装置-三梯环境 | 液压升降平台_剪叉式液压/导轨式升降机_传菜机定做「宁波日腾升降机厂家」 | 宝元数控系统|对刀仪厂家|东莞机器人控制系统|东莞安川伺服-【鑫天驰智能科技】 | LZ-373测厚仪-华瑞VOC气体检测仪-个人有毒气体检测仪-厂家-深圳市深博瑞仪器仪表有限公司 | 哲力实业_专注汽车涂料汽车漆研发生产_汽车漆|修补油漆品牌厂家 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 杭州中央空调维修_冷却塔/新风机柜/热水器/锅炉除垢清洗_除垢剂_风机盘管_冷凝器清洗-杭州亿诺能源有限公司 | 济宁工业提升门|济宁电动防火门|济宁快速堆积门-济宁市统一电动门有限公司 | 家庭教育吧-在线家庭教育平台,专注青少年家庭教育 | 济南办公室装修-厂房装修-商铺装修-工装公司-山东鲁工装饰设计 | 干粉砂浆设备_干混砂浆生产线_腻子粉加工设备_石膏抹灰砂浆生产成套设备厂家_干粉混合设备_砂子烘干机--郑州铭将机械设备有限公司 | 手持式3d激光扫描仪-便携式三维立体扫描仪-北京福禄克斯 | 广东佛电电器有限公司|防雷开关|故障电弧断路器|智能量测断路器 广东西屋电气有限公司-广东西屋电气有限公司 | 门禁卡_智能IC卡_滴胶卡制作_硅胶腕带-卡立方rfid定制厂家 | 【星耀裂变】_企微SCRM_任务宝_视频号分销裂变_企业微信裂变增长_私域流量_裂变营销 | 标准品网_标准品信息网_【中检计量】 | 协议书_协议合同格式模板范本大全 | 济南侦探调查-济南调查取证-山东私家侦探-山东白豹调查咨询公司 密集架|电动密集架|移动密集架|黑龙江档案密集架-大量现货厂家销售 | 报警器_家用防盗报警器_烟雾报警器_燃气报警器_防盗报警系统厂家-深圳市刻锐智能科技有限公司 | 壹作文_中小学生优秀满分作文大全 | 宁夏档案密集柜,智能密集柜,电动手摇密集柜-盛隆柜业宁夏档案密集柜厂家 | 广东恩亿梯电源有限公司【官网】_UPS不间断电源|EPS应急电源|模块化机房|电动汽车充电桩_UPS电源厂家(恩亿梯UPS电源,UPS不间断电源,不间断电源UPS) | 校园文化空间设计-数字化|中医文化空间设计-党建|法治廉政主题文化空间施工-山东锐尚文化传播公司 | 不锈钢电动球阀_气动高压闸阀_旋塞疏水调节阀_全立阀门-来自温州工业阀门巨头企业 | 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 焊管生产线_焊管机组_轧辊模具_焊管设备_焊管设备厂家_石家庄翔昱机械 | 标准件-非标紧固件-不锈钢螺栓-非标不锈钢螺丝-非标螺母厂家-三角牙锁紧自攻-南京宝宇标准件有限公司 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 苏州教学设备-化工教学设备-环境工程教学模型|同科教仪 | 儋州在线-儋州招聘找工作、找房子、找对象,儋州综合生活信息门户! | 专业生产动态配料系统_饲料配料系统_化肥配料系统等配料系统-郑州鑫晟重工机械有限公司 | 成都装修公司-成都装修设计公司推荐-成都朗煜装饰公司 | 课件导航网_ppt课件_课件模板_课件下载_最新课件资源分享发布平台 |