2011-09-27 56 views
1

我想在一定數量的字符之後打破一行,比如在大約20個字符之後它應該在PHP中最靠近句號(。)之後斷行。用PHP包裝大文本

我有這樣的文字:。

一個段落如下像「我們的客戶服務部將幫助您 與您可能遇到的任何問題買家負責來回 航運我們提供免費的UPS或USPS地面運輸到大陸 美國我們船內支付的1個工作日。所有其它運輸 收費(參見購買細節項目的拍賣)。所有訂單 獲得UPS或USPS追蹤號碼。

這是我到目前爲止已經試過:

$desc = $listings['Item']['Description']; 
echo wordwrap($desc,250,"<br />\n"); 
+0

如果你回來選擇答案,將不勝感激,哈哈! –

回答

-1
<?php 
    $text = "Our Customer service dept. will help you with any issue you might have. Buyer is responsible for return shipping. We offer free UPS or USPS ground shipping to the continental U.S. We ship within 1 business day of payment. All other shipping rates apply (see auction of item purchased for details). All orders get a UPS or USPS tracking number."; 

    $textTrimmed = substr($text, 20) // The number of chars 
    echo $textTrimmed 
?> 

or you can use a function 

function trimTextAfter($text, $numberOfChar){ 
    echo substr($text,$numberOfChar); 
} 
+0

這不會在20個字符後出現的第一個句點之後添加一個換行符。 –

+0

正如你給的長度是20個字符。我想打破20個字符,最近的完整(。)。這意味着「它必須在部門之後打破一條線」)..每隔20個字符最近的fullstop必須換新線 – Viralk

0

使用wordwrap()字符的給定數目之前,包裝你的字符串。如果你想通過點(。)分割,你可以用explode()implode()做一些事情。

+0

讓我們看看你得到多遠,如果你先嚐試自己 – Rijk

+0

<?php $ desc = $ listings [ 'Item'] ['Description']; echo wordwrap($ desc,250,「
\ n」);?> – Viralk

0

我認爲正則表達式是給你想要的最簡單的方法。考慮到這個問題,我相當積極,你要麼從來沒有聽說過它,要麼根本不知道它是如何工作的。

因爲它非常複雜,我願意幫助你,直到你完全按照你想要的方式管理它。

我跑了一些測試,這對我有用。

echo preg_replace('/(\.{20}?|.{10,20}?\.)/', '$1<br />', $desc); 

這種單一的代碼行提出分手標籤要麼當達到20個字符時,有一個點後面加一個空格,如果有超過10個字符之前,以避免單個字線。

你給將從去的示例文本:。

一個段落如下像「我們的客戶服務部將幫助您解決任何問題,你可能有買家負責來回運費我們提供免費的UPS或USPS地面運輸到美國大陸我們船內支付的1個工作日內所有其他貨運收費(參見購買細節項目的拍賣)所有訂單獲得UPS或USPS追蹤號碼

到。:

A Paragraph follows like "Our Customer service dept.<br /> 
will help you with any issue you might have.<br /> 
Buyer is responsible for return shipping.<br /> 
We offer free UPS or USPS ground shipping to the continental U.S.<br /> 
We ship within 1 business day of payment.<br /> 
All other shipping rates apply (see auction of item purchased for details).<br /> 
All orders get a UPS or USPS tracking number. 

讓我知道如果這是你想要的方式!