How do I get a random result from a preg_match_all?

(Sorry if the title is pretty useless)

I have this function to get the first image from a random post in WordPress. This works great, but now I need it to select a random image from all the matches, rather than the first.
(I’m running this function in a query_posts loop to select the categories)

Read More
// 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;
}

So, any ideas, links, tips & tricks on how to select a random result from the matches results?

Related posts

Leave a Reply

3 comments

  1. Match everything, and then use array_rand() to get a random match.

    Assuming you use the PREG_SET_ORDER flag with preg_match_all then to get a random link.

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

    It is important to note that array_rand() returns a random key, not a random value.

  2. Try with this

    // 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;
    }
    
  3. You should be able to use array_rand() to return a random key from the $matches array. You may need to change the format of the array you get from preg_match_all().

    You can use PREG_PATTERN_ORDER then pass $matches[$x] to array_rand() – where $x is the match group you want (0 being the full match, 1 being the first subgroup). In this case array_rand() will return a key, and you can access the random data using $matches[$x][$rand_key].

    Alternatively, using PREG_SET_ORDER, you would pass $matches to array_rand(), then use the returned key to access any subgroup of the match. $matches[$rand_key][$x]

    Note that you’re not getting a random value, you’re getting the array key to a random value. And as noted by others, you can simply use the array_rand() function directly when accessing the array, which is an easy cut/paste solution. However, I hope this longer explanation sheds light on what the code is doing.