3

I am having trouble matching the space after content="Wordpress in the following regex

$metatag = '<meta name="generator" content="WordPress 4.8.2">';
$metaregex = '/<meta.*?content="Wordpress.(?<version>.*?)"/';

preg_match($metaregex, $metatag, $matches);

print_r($matches);

2 Answers 2

5

It's a typo mistake. Instead of:

$metaregex = '/<meta.*?content="Wordpress.(?<version>.*?)"/';

It should be:

$metaregex = '/<meta.*?content="WordPress.(?<version>.*?)"/';

Notice Wordpress vs WordPress.


Or you can ignore case by using the i modifier:

$metaregex = '/<meta.*?content="wordpress.(?<version>.*?)"/i';
  • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Sign up to request clarification or add additional context in comments.

Comments

2

A better approach to this would be using a parser and then use a regex on just the attributes value.

$html = '<meta name="generator" content="WordPress 4.8.2">';
$dom = new DOMDocument;
$dom->loadHTML($html);
$heads = $dom->getElementsByTagName('meta');
foreach ($heads as $head) {
    if($head->getAttribute('name') == 'generator' && preg_match('/wordpress (?<version>(?:\d+\.?)+)/i', $head->getAttribute('content'), $version)) {
        die($version['version']);
    }
}

Demo: https://3v4l.org/YlsFP

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.