2016-05-24 62 views
-1

這是我的代碼,目前無法正常工作。我怎樣才能使它工作?我的願望是使輸出像一個字符串(當然我知道如何「轉換」數組是string):帶有一個輸出的多陣列

話改變,添加和刪除,使之

代碼:

<?php 

header('Content-Type: text/html; charset=utf-8'); 
$text = explode(" ", strip_tags("words altered added and removed to make it")); 
$stack = array(); 

$words = array("altered", "added", "something"); 
foreach($words as $keywords){ 
    $check = array_search($keywords, $text); 
    if($check>(-1)){ 
    $replace = " ".$text[$check].","; 
    $result = str_replace($text[$check], $replace, $text); 
    array_push($stack, $result); 
    } 
} 

print_r($stack); 
?> 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => words 
      [1] => altered, 
      [2] => added 
      [3] => and 
      [4] => removed 
      [5] => to 
      [6] => make 
      [7] => it 
     ) 

    [1] => Array 
     (
      [0] => words 
      [1] => altered 
      [2] => added, 
      [3] => and 
      [4] => removed 
      [5] => to 
      [6] => make 
      [7] => it 
     ) 
) 
+1

您的期望輸出究竟是什麼?你的問題很不清楚。 – Milanzor

+0

你可以使用implode('',$ stack [0]); –

+0

implode僅輸出第一個數組結果 – Nick

回答

1

沒有更多的解釋是這樣簡單:

$text = strip_tags("words altered added and removed to make it"); 
$words = array("altered", "added", "something"); 

$result = $text; 
foreach($words as $word) { 
    $result = str_replace($word, "$word,", $result); 
} 
  • 不爆炸源字符串
  • 循環的話,用這個詞替換詞,並添加逗號

或放棄循環方法:

$text = strip_tags("words altered added and removed to make it"); 
$words = array("altered", "added", "something"); 

$result = preg_replace('/('.implode('|', $words).')/', '$1,', $text); 
  • 被爆在交替的話(OR)創建一個模式操作|
  • $1和逗號替換找到的字
+0

謝謝SIR!這是真正的答案! – Nick

0

您可以使用iterator

// Array with your stuff. 
$array = []; 

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
foreach($iterator as $value) { 
    echo $v, " "; 
} 
+0

您的建議不起作用,請在下次在此處發佈代碼之前運行代碼。 – Nick

0

你原來的做法應該有一些修改工作。代之以循環展開字符串中的單詞。對於每一個,如果它在要修改的單詞數組中,請添加逗號。如果不是,不要。然後,修改後的(或不)字進入堆棧。

$text = explode(" ", strip_tags("words altered added and removed to make it")); 
$words = array("altered", "added", "something"); 

foreach ($text as $word) { 
    $stack[] = in_array($word, $words) ? "$word," : $word; 
}