2009-11-13 40 views
3

我遇到了一段文本并将它拆分为单词/句子以发送多条文本消息的逻辑问题。每条短信最多只能有160个字符。我想干净地打破一个段落。将段落分割为160个字符片段以用于文本消息

这里是解决方案(感谢Leventix!):

public static function splitStringAtWordsUpToCharacterLimit($string, $characterLimit) { 
    return explode("\n", wordwrap($string, $characterLimit)); 
} 

回答

6

您可以通过使用换行wordwrap,然后explode

+0

我向你的答案鞠躬:)。我喜欢这个网站,它通过回答这些问题使我成为一个更好的程序员,然后找到人们解决他们遇到的问题的方法。非常酷Leventix! – 2009-11-14 06:11:14

0

为什么你需要在这里使用正则表达式!?

您所要做的就是将字符串拆分为多条文本消息。所以你会做这样的事情(我不记得确切的语法,我的PHP是生锈)length($string)/$charmax,然后只是串,很多时候到一个数组中,并返回该数组

+0

他想避免在一个词的中间打破,我想。 – 2009-11-13 21:08:35

0
<?php 
$string = str_repeat('Welcome to StackOverFlow, Heres Your Example Code!', 6); 

print_r(str_split($string, 160)); 

# You could also Alias the function. 
function textMsgSplit($string, $splitLen = 160) { 
    return str_split($string, $splitLen); 
} 
?> 
3

这是我使用的功能,

function sms_chunk_split($msg) { 
    $msg = preg_replace('/[\r\n]+/', ' ', $msg); 
    $chunks = wordwrap($msg, 160, '\n'); 
    return explode('\n', $chunks); 
} 

它将一条长的SMS消息分成160个字节的块,在字边界处分割。