Using WordPress ‘get_tag_regex()’ PHP function

The get_tag_regex() WordPress PHP function returns a RegEx pattern to liberally match an opening HTML tag.

Usage

get_tag_regex($tag);

Example:

Input:

get_tag_regex('video');

Output:

<(video)[\s\w<>=\/\!]*>

Parameters

  • $tag (string) – Required. An HTML tag name. Example: 'video'.

More information

See WordPress Developer Resources: get_tag_regex()

Examples

Match Image Tags

Find all opening image tags in a string.

$content = 'Here is an image <img src="image.jpg" alt="An Image"> and another <img src="another.jpg" alt="Another Image">';
$regex = get_tag_regex('img');
preg_match_all("/$regex/", $content, $matches);
print_r($matches);

Match Paragraph Tags

Find all opening paragraph tags in a string.

$content = '<p>Hello, world!</p><p>Another paragraph here</p>';
$regex = get_tag_regex('p');
preg_match_all("/$regex/", $content, $matches);
print_r($matches);

Match Custom Tags

Find all opening custom tags in a string.

$content = '<custom-tag>Some content</custom-tag><custom-tag>Another content</custom-tag>';
$regex = get_tag_regex('custom-tag');
preg_match_all("/$regex/", $content, $matches);
print_r($matches);

Match Anchor Tags

Find all opening anchor tags in a string.

$content = 'Visit our <a href="https://example.com">website</a> and <a href="https://example.com/contact">contact us</a>';
$regex = get_tag_regex('a');
preg_match_all("/$regex/", $content, $matches);
print_r($matches);

Match Header Tags

Find all opening header tags (h1, h2, h3) in a string.

$content = '<h1>Title</h1><h2>Subtitle</h2><h3>Section</h3>';
$header_tags = ['h1', 'h2', 'h3'];
foreach ($header_tags as $tag) {
    $regex = get_tag_regex($tag);
    preg_match_all("/$regex/", $content, $matches);
    print_r($matches);
}