以123,234,345等格式转换字符串

时间:2014-11-15 08:13:20

标签: php

我有一个如下所示的字符串

$string = "hi hello how are you ? hope you";

我需要结果如下面的数组

hi hello how
hello how are
how are you
are you hope
you hope you.

我尝试了类似下面的内容

$exp = explode(" ",$string);

foreach($exp as $lol)

{

//now i have no idea what to do..some 1 guide me please.

}

2 个答案:

答案 0 :(得分:1)

尝试使用array_shift并运行循环两次。

注意:阅读答案中的评论,因为我解释了为什么我这样写。

<?php

$string = "hi hello how are you hope you";

$exp = explode(" ",$string);

for ($i=0; $i<(count($exp)+3);$i++)//as you want to print three value in 
//each loop your loop should run three more time than 
//the number of element you got in your original array
{

    echo '<br/>';
    for($k=0;$k<3;$k++)
    {

         echo ' ';//added the space to see
        print_r($exp[$k]);//to see the result
    }
    $value=  array_shift($exp);//after printing the result remove the 
    //first element from the array. so this will remove the first elemenet after 
    //each result.
}

您的结果将如下所示

hi hello how
hello how are
how are you
are you hope
you hope you

答案 1 :(得分:0)

这段代码示例给出了2个级别。没有foreach的内容是没有单词。

$vari = "hai hello how?";

$vari = str_replace("?", "", $vari);
$vars = explode(" ", $vari);
$varp = $vars;
foreach ($vars as $p_i=>$p_v){
    foreach($varp as $c_i=>$c_v){
        if($p_i!=$c_i){
            echo $p_v." ".$c_v."<br/>";
        }
    }
}

<强> RESULT

hai hello
hai how
hello hai
hello how
how hai
how hello

你可以将foreach放在另一个foreach中以获得更多的单词。