2010-01-25 23 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