Y
Y
Ysery2021-07-16 11:01:44
PHP
Ysery, 2021-07-16 11:01:44

Regular expression, how to add an exception?

I use this code in WordPress. Determines the first image from the article and uses it as the post image. But in some articles there is an information block, and there is a picture "info.png" or "warning.png" in it. How to modify the script to skip this picture ("info.png" or "warning.png"), if it exists.

function get_first_post_image()
{
    global $post, $posts;
    $first_img = "";
    ob_start();
    ob_end_clean();
    if (
        preg_match_all(
            '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
            $post->post_content,
            $matches
        )
    ) {
        $first_img = $matches[1][0];
        return $first_img;
    } else {
        $first_img = "https://sample.com/images/post-default.png";
        return $first_img;
    }
}


Here's what I got but it doesn't work

function get_post_image()
{
    global $post, $posts;
    $first_img = "";
    ob_start();
    ob_end_clean();
    if (
        preg_match_all(
            '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
            $post->post_content,
            $matches
        )
    ) {
        if ($matches[1][0] === "info.png" || $matches[1][0] === "warning.png") {
            $first_img =
                $matches[2][0] ?? "https://sample.com/media/post-default.png";
            return $first_img;
        } else {
            $first_img = $matches[1][0];
            return $first_img;
        }
    }
}


PHP Version 7.1.11

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-07-16
@Ysery

Parsing arbitrary html through regular expressions is already a thankless task, and if you also try to complicate this regular expression, it's even easier to shoot yourself in the foot.
Don't be smart:

if ($matches[1][0] === 'info.png' || $matches[1][0] === 'warning.png') {
  return $matches[2][0] ?? 'https://sample.com/images/post-default.png';
} else {
  return $matches[1][0];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question