PHP之string之wordwrap()函数使用

本文介绍了 PHP 中的 wordwrap 函数,该函数用于将字符串按照指定长度进行换行处理。文章通过多个示例展示了如何使用该函数,并解释了如何控制换行字符、列宽度以及是否在长单词上强制换行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

wordwrap

  • (PHP 4 >= 4.0.2, PHP 5, PHP 7)
  • wordwrap — Wraps a string to a given number of characters
  • wordwrap — 打断字符串为指定数量的字串

Description

string wordwrap ( 
    string $str [, 
    int $width = 75 [, 
    string $break = "\n" [, 
    bool $cut = FALSE ]]] 
    )
//Wraps a string to a given number of characters using a string break character.
//使用字符串断点将字符串打断为指定数量的字串。

Parameters

str

  • The input string.
  • 输入字符串。

width

  • The number of characters at which the string will be wrapped.
  • 列宽度。

break

  • The line is broken using the optional break parameter.
  • 使用可选的 break 参数打断字符串。

cut

  • If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example). When FALSE the function does not split the word even if the width is smaller than the word width.
  • 如果 cut 设置为 TRUE,字符串总是在指定的 width 或者之前位置被打断。因此,如果有的单词宽度超过了给定的宽度,它将被分隔开来。(参见第二个范例)。 当它是 FALSE ,函数不会分割单词,哪怕 width 小于单词宽度。

Return Values

  • Returns the given string wrapped at the specified length.
  • 返回打断后的字符串。

Examples

<?php
/**
 * Created by PhpStorm.
 * User: zhangrongxiang
 * Date: 2018/3/8
 * Time: 下午9:27
 */

$text    = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap( $text, 20, "\n" );
//The quick brown fox
//jumped over the lazy
//dog.
echo $newtext . PHP_EOL;

$text    = "A very long woooooooooooord.";
$newtext = wordwrap( $text, 8, "\n", false );
//A very
//long
//woooooooooooord.
echo $newtext . PHP_EOL;
$newtext = wordwrap( $text, 8, "\n", true );
//A very
//long
//wooooooo
//ooooord.
echo $newtext . PHP_EOL;

$str = "hello world hello php";
//hello-world-hello-php
echo wordwrap( $str, 5, "-", false ) . PHP_EOL;
//hello world hello php
echo wordwrap( $str ) . PHP_EOL;
//hello
//world
//hello
//php
echo wordwrap( $str, 3 ) . PHP_EOL;

See

All rights reserved

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值