2011-05-05 31 views
0

在展開的陣列中匹配。我以前曾使用@HSZ的this matter獲得一些幫助,但無法使用現有陣列的解決方案。我試圖做的是爆炸報價,使所有單詞大寫加上每個單詞索引值,只回聲我定義然後內爆。用最簡單的話來說,總是刪除引號內的第4個單詞或第3個和第4個單詞...這可能也可以用正則表達式來完成。定義的str_word_count的打印列表按索引

實施例:

Hello [1] => World [2] => This [3] => Is [4] => a [5] => Test) 6只輸出I定義的數字,例如1 - (你好)[2] - (世界)留出[3],[4],[5]和[6]或這是隻留下的Hello World,或1和[6]你好測試...

如測試

echo $data[1] + ' ' + $data[6]; //Would output index 1 and 6 Hello and Test 

現有代碼

if (stripos($data, 'test') !== false) { 
$arr = explode('"', $data); 

for ($i = 1; $i < count($arr); $i += 2) { 
$arr[$i] = strtoupper($arr[$i]);  
$arr[$i] = str_word_count($arr, 1); // Doesnt work with array of course. 
} 

$arr = $matches[1] + ' ' + $matches[6]; 
$data = implode('"', $arr); 
} 
+1

我不知道我理解這個問題? – Niklas 2011-05-05 14:30:32

+0

一個'str_word_count'期望一個字符串不是一個數組,但我的輸入已經暫時分解爲一個數組......我基本上試圖返回一個數組的索引字計數值。因此,Hello World「這是一個測試」,帶有echo'$ matches [4]'的Hello World將成爲Hello World「測試」。 – 2011-05-05 14:42:21

回答

1

假設$data'Hello world "this is a test"'$arr = explode('"', $data)將是相同的:

$arr = array (
    [0] => 'Hello World', 
    [1] => 'This is a test' 
) 

如果你想要做的事情this is a test,你可以使用類似$testarr = explode(' ', $arr[1]);爆發出來。

然後你可以這樣做:

$matches = array(); 
foreach ($testarr as $key => $value) { 
    $value = strtoupper($value); 
    if(($key+1)%4 == 0) { // % is modulus; the result is the remainder the division of two numbers. If it's 0, the key+1 (compensate for 0 based keys) is divisible by 4. 
     $matches[] = $value; 
    } 
} 
$matches = implode('"',$matches); 
+0

對不起,爆炸從報價開始......並在修改後添加回來。你好世界「這是一個測試」 – 2011-05-05 14:44:38

+0

另外我的代碼是不正確的,即時嘗試計算引號內的每個單詞,得到每個單詞的索引,並通過留下某些值基本省略單詞。最簡單的說,總是刪除引號中的第四個單詞...... – 2011-05-05 14:52:41

+0

請參閱我編輯的答案。 – Shauna 2011-05-05 15:23:42