我想在第一行打印前两个字符串数组的名称,并在下一行打印剩余的名称。
<?php
$array = array("johnny bairstow alex hales jonh marush","Marcelo nash tim pane alexender","chaudary Mian
Muhammad Aqeel shaib ");
for ($i=0; $i < count($array) ; $i++) {
$len = strlen($array[$i]);
$string = $array[$i];
for ($j = 8; $j < 9 ; $j++) {
$string[$j] ='\n';
}
echo $string."</br>";
}
?>
输出应该是:
johnny doe
alex hales jonh marush
Marcelo Nash
tim pane alexender
chaudary Mian
Muhammad Aqeel shaib
答案 0 :(得分:0)
如果你确定数组中的字符串总数,你可以使用explode()函数
<?php
$array = array("johnny doe alex hales","Marcelo nash tim pane","Mian
Muhammad Aqeel shaib");
for ($i=0; $i < count($array) ; $i++) {
$len = strlen($array[$i]);
$string = explode(" ", $array[$i]);
echo $string[0] . " " . $string[1] . "<br>" .
$string[2] . " " . $string[3] . "<br>";
}
?>
注意,如果数组内没有4个字符串则返回错误
修改强>
执行此示例,您可以使用3个总字符串而不返回错误。我建议你使用这段代码
<?php
$array = array("johnny doe alex ","Marcelo nash tim pane","Mian
Muhammad Aqeel shaib");
for ($i=0; $i < count($array) ; $i++) {
$len = strlen($array[$i]);
$string = explode(" ", $array[$i]);
for( $n=0; $n < count($string); $n++ ){
echo $string[$n];
echo ( $n & 1 ) ? '<br>' : ' ' ;
}
}
?>
答案 1 :(得分:0)
试试这个:
<?php
$array = array("johnny doe alex hales","Marcelo nash tim pane","Mian
Muhammad Aqeel shaib");
foreach($array as $string) {
foreach(explode(' ', $string) as $index => $name) {
$br_new_string = true;
echo $name . ' ';
if(1 == $index % 2) {
echo '<br>';
$br_new_string = false;
}
}
echo $br_new_string ? '<br>' : '';
}
输出:
johnny doe
alex hales
Marcelo nash
tim pane
Mian Muhammad
Aqeel shaib
答案 2 :(得分:0)
另一种简短的解决方案:
$data = ["johnny doe alex hales", "Marcelo nash tim pane", "Mian Muhammad Aqeel shaib"];
// Make them all into one string and explode the values on space
$names = explode(' ', implode(' ', $data));
for ($i = 0; $i < count($names); $i++) {
// Echo the name for the index, add one to the index and echo the next one.
echo $names[$i++] . ' ' . $names[$i] . '<br />';
}
答案 3 :(得分:0)
您可以通过查找字符串中的第二个空格,然后将其替换为您想要的内容来实现:
foreach($array as $string)
{
$sndSpacePos = strpos($string, ' ', strpos($string, ' ')+1); //the offset for strpos is set right after the first space so it found the second one
echo substr($string, 0, $sndSpacePos).'<br>'.substr($string, $sndSpacePos+1).'<br>'; //echo the concatenation of string parts before and after the second space with a <br> in the middle
}
避免使用爆炸和第二个循环。
答案 4 :(得分:0)
array (
0 => 'johnny bairstow',
1 => 'alex hales jonh marush',
2 => 'Marcelo nash',
3 => 'tim pane alexender',
4 => 'chaudary Mian',
5 => 'Muhammad Aqeel shaib',
)
输出:
{{1}}