2010-01-25 103 views
1

(很抱歉,如果標題是相當無用)如何從preg_match_all中獲得隨機結果?

我有這樣的功能,從在WordPress隨機獲得後第一個圖像。這很好,但現在我需要它從所有匹配中選擇一個隨機圖像,而不是第一個。 (我運行這個功能在query_posts循環選擇類別)

// Get first image in post 
function catch_that_image() { 
    global $post, $posts; 
    $first_img = ''; 
    ob_start(); 
    ob_end_clean(); 
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
    $first_img = $matches [1] [0]; 

    //no image found display default image instead 
    if(empty($first_img)){ 
     $first_img = "/images/default.jpg"; 
    } 

    // Or, show first image. 
    return $first_img; 
} 

因此,任何想法,鏈接,提示&技巧如何選擇比賽結果的隨機結果?

回答

0

匹配所有內容,然後使用array_rand()獲得隨機匹配。

假設您對preg_match_all使用PREG_SET_ORDER標誌,然後獲取一個隨機鏈接。

$randomImage = $matches[array_rand($matches)][0]; 

需要注意的是array_rand()返回一個隨機密鑰,而不是一個隨機值是非常重要的。

+0

工作正常!對於其他人,這是最終的代碼。 '//獲取帖子中的第一個圖片 function catch_that_image(){ \t global $ post,$ posts; \t $ first_img =''; \t ob_start(); \t ob_end_clean(); \t $ output = preg_match_all('/ /i',$ post-> post_content,$ matches); \t $ first_img = $ matches [1] [0]; \t \t //沒有發現圖像顯示缺省圖像,而不是 \t如果(空($ first_img)){ \t \t $ first_img =「/圖片/默認值。JPG「; \t} \t \t //或者,顯示第一圖像 \t回$匹配[1] [array_rand($比賽[1]);} 」 – PaulDavis 2010-01-25 14:53:50

+0

好了,我不能讓代碼(UX錯誤?) 下面是最終的代碼,格式不錯。http://kodery.com/119 – PaulDavis 2010-01-25 15:07:24

0

與此

// Get first image in post 
function catch_that_image() { 
    global $post, $posts; 
    $first_img = ''; 
    ob_start(); 
    ob_end_clean(); 
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 

    //no image found display default image instead 
    if(!$output){ 
     $first_img = "/images/default.jpg"; 
    } //or get a random image 
    else $first_img=$matches[1][array_rand($matches[1])]; 

    return $first_img; 
} 
+0

不幸的是,這返回'0' – PaulDavis 2010-01-25 14:50:05

0

嘗試你應該能夠使用array_rand()返回從$matches陣列隨機密鑰。您可能需要更改從preg_match_all()獲得的陣列格式。

您可以使用PREG_PATTERN_ORDER然後傳遞到$matches[$x]array_rand() - 在$x是匹配組你想(0是全場比賽,1爲第一小組)。在這種情況下,array_rand()將返回一個密鑰,並且您可以使用$matches[$x][$rand_key]訪問隨機數據。

或者,使用PREG_SET_ORDER,您可以將$matches傳遞給array_rand(),然後使用返回的鍵訪問任何匹配的子組。 $matches[$rand_key][$x]

注意,你沒有得到一個隨機,你得到的數組鍵爲隨機值。正如其他人所指出的那樣,您可以在訪問陣列時直接使用array_rand()函數,該陣列是一個易於剪切/粘貼的解決方案。但是,我希望這個更長的解釋能夠說明代碼在做什麼。

+0

啊,對於我可憐的術語感到抱歉。一直在使用PHP幾個月,我會試試你的答案。 – PaulDavis 2010-01-25 14:48:47