我有两种类型的输入字符串:
一行中的字符串: 例如:
$ STR = Hello12345Hello12345Hello12345
2.string with new line ("\n\r")
例如:
$str = '
Hello
12345
Hello
12345
Hello
12345'
我现在使用的方式是:
选项1:
if $str one line:
join("\n\r",str_split($str,5))
else:
explode("\n\r",$str)
尝试
选项2:
preg_match_all('/[^\r\n]{0,5}([\r\n]*)/',$str , $matches);
$arr = $matches[0];
我应该使用哪一个?
答案 0 :(得分:2)
这样的东西?
$str = 'Hello12345Hello12345Hello12345';
$arr = str_split($string, 5);
$str = PHP_EOL . implode(PHP_EOL, $arr);
答案 1 :(得分:1)
$str1 = 'Hello12345Hello12345Hello12345';
$array1 = str_split($str1, 5);
$str2 = '
Hello
12345
Hello
12345
Hello
12345';
$array2 = array_filter(array_map(function($v) {
return trim($v);
}, explode("\n", $str2)));