1

這是代碼:正則表達式(preg_match_all)和陣列

<?php 
    $matchWith = "# http://videosite.com/id1 http://videosite.com/id2 # # http://videosite.com/id3 http://videosite.com/id4 #"; 

    preg_match_all('%(#)\shttp://videosite\.com/(\w+)\r{0,1}\shttp://videosite\.com/(\w+)\r{0,1}\s(#)%', $matchWith, $result); 
    foreach($result[2] as $value) 
    { 
    print '<a href="http://videosite.com/'.$value.'"> 
    First Part 
    </a>';   

    } 
    foreach($result[3] as $value) 
    { 
    print '<a href="http://videosite.com/'.$value.'"> 
    Second Part 
    </a>';   
    } 
    ?> 

問題:

我希望它顯示是這樣的:第一部分,第二部分和第一部分第二部分。

但它顯示它是這樣的:第一部分,第一部分,第二部分,第二部分。

我真的很希望你明白。 謝謝

回答

2
<?php 
    $matchWith = "# http://videosite.com/id1 http://videosite.com/id2 # # http://videosite.com/id3 http://videosite.com/id4 #"; 

    preg_match_all('%(#)\shttp://videosite\.com/(\w+)\r{0,1}\shttp://videosite\.com/(\w+)\r{0,1}\s(#)%', $matchWith, $result); 
    for($i = 0; $i < count($result[2]); $i++){ 
     print '<a href="http://videosite.com/'.$result[2][$i].'"> 
     First Part 
     </a>'; 
     print '<a href="http://videosite.com/'.$result[3][$i].'"> 
     Second Part 
     </a>';  
    } 
    ?> 

答案假定兩個數組有一個並行結構。

編輯:改變$ i ==爲$ i ++

+0

for循環應該說'$ i ++'而不是'$ i ==',但除此之外,這是正確的。 –

+0

太棒了!只是我正在尋找的答案!你們好棒! :) – Helena

0

這是你想要的嗎?

for($i = 0; $i < count($result); $i++) 
{ 
    print '<a href="http://videosite.com/'.$result[$1][2].'"> 
    First Part 
    </a>';   

    print '<a href="http://videosite.com/'.$result[$1][3].'"> 
    Second Part 
    </a>'; 
} 
+0

我不確定,因爲我收到一條錯誤消息。但有人剛剛發佈了我正在尋找的答案。還是謝謝你:) – Helena