如何在PHP中从数组元素中拆分字符串?
问题描述:
I want to split array element's string. I have to split it at the fifth character, but if it's in the middle of the word, split it at the nearest whitespace. Like this:
// I have array like these
$array={"How are you ?","I am fine."};
//I want output like if we take length = 5.
$array1 = {"How are","you ?","I am fine."}; // array1[0] =how a should be array1[0] = how are .
我想拆分数组元素的字符串。 我必须将它拆分为第五个字符,但如果它位于单词的中间,则将其拆分为最近的空格。 像这样: p>
//我有像这样的数组
$ array = {“你好吗?”,“我很好。”};
/ n /我想要输出,如果我们取长度= 5.
$ array1 = {“怎么样”,“你?”,“我很好。”}; // array1 [0] =应该如何为array1 [0] =如何。
code> pre>
div>
答
Look for nearest whitespace to the fifth character. Then return the first part from 0 until that character and put it into new array. Then put the second chunk (the one until the end) into the same array.
foreach ($array as $val) {
$strpos = strpos($val, " ", 5);
$array1[] = substr($val, 0, $strpos);
$array1[] = substr($val, $strpos+1, strlen($val));
}