我想改变字符串的方向,例如我想要HELLO WORLD这样的字样:
H W
E O
L R
L L
O D
我这样做但不起作用!
$word=preg_split('/s',string);
$hor_letter=preg_split('//u,'$word);
foreach ($hor_letter as $letter) {
$vert_letter=$letter."\n";
}
结果是:
H
E
L
L
O
W
O
R
L
D
答案 0 :(得分:1)
多田!试试这个,解释在代码中的注释中:
$str = "HELLO HOW YA DOING WORLD?";
// Convert $str to an array of rows of letters.
$strWords = explode(' ', $str);
$strLettersRowsArr = array_map('str_split', $strWords);
// Get maximium number of rows of letters e.g. `strlen("WORLD?")` => `6`.
$maxRows = 0;
foreach ($strLettersRowsArr as $lettersArr) {
if (count($lettersArr) > $maxRows) {
$maxRows = count($lettersArr);
}
}
// Pad out the elements of $strLettersRowsArr with spaces that aren't as long as the longest word.
// e.g.
// from:
// [
// ['H', 'e', 'l', 'l', 'o'],
// ['d', 'u', 'd', 'e'],
// ]
// to:
// [
// ['H', 'e', 'l', 'l', 'o'],
// ['d', 'u', 'd', 'e', ' '],
// ]
foreach ($strLettersRowsArr as $key => &$lettersArr) {
while (count($lettersArr) < $maxRows) {
$lettersArr[] = ' ';
}
}
unset($lettersArr);
// Get the columns of letters.
// e.g.
// from:
// [
// ['H', 'e', 'l', 'l', 'o'],
// ['w', 'o', 'r', 'l', 'd'],
// ]
// to:
// [
// ['H', 'w'],
// ['e', 'o'],
// ['l', 'r'],
// ['l', 'l'],
// ['o', 'd'],
// ]
$strLettersColumnsArr = [];
for ($row = 0; $row < $maxRows; $row++) {
$strLettersColumnsArr[] = array_column($strLettersRowsArr, $row);
}
// Print out letter columns.
foreach ($strLettersColumnsArr as $lettersColumnArr) {
foreach ($lettersColumnArr as $letter) {
echo "$letter ";
}
echo "\n";
}
输出:
H H Y D W
E O A O O
L W I R
L N L
O G D
?