Jump to content

Improve regex for META tags


boby

Recommended Posts

Hello,

I am writing a script that out of a webpage.
Because the "get_meta_tags" function is very slow and cannot handle very well line breaks, I'm using following code:

Can someone please review this regex and if possible improve or suggest something better?
[code=php]<?php

preg_match_all ('/<[\s]*meta[\s]*name[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*content[\s]*=[\s]*["\']?([^>"\']*)["\']?[\s]*[\/]?[\s]*>/si', $content, $matches);

?>[/code]

Thank you very much!
Boby
Link to comment
https://forums.phpfreaks.com/topic/16639-improve-regex-for-meta-tags/
Share on other sites

This what I have to get the meta tag contents:
[code=php:0]<?php

$text = '<meta name="keywords" content="PHP, MySQL, bulletin, board, free, open, source, smf, simple, machines, forum" />';

if(preg_match("#<meta([^>]*)>#si", $text, $matches))
{
    //echo '<pre>' . htmlentities(print_r($matches, true)) . '</pre><br /><br />';

    //$matches[1] is what stores the contents of the meta tag
    $matches[1] = str_replace("/", '', $matches[1]);

    // put each attribute and its value into an array
    $attrs = preg_split("#(\"\s)#i", trim($matches[1]));

    // "e now create a meta array. The format of the array will be:
    // Array([attribute_name] => [attribute_value])
    foreach($attrs as $attr)
    {

        // we now get the attribute name and attribute value in sperate variables
        list($attr_name, $attr_value) = explode("=", $attr);

        // we create our meta array, trimming of any double quotes remaining in the attribute value string.
        $meta[$attr_name] = trim($attr_value, '"');
    }

    echo '<pre>' . print_r($meta, true) . '</pre>';
}

?>[/code]

I use the meta tag from the forum for reference.

The code outputs the following:
[code]Array
(
    [name] => keywords
    [content] => PHP, MySQL, bulletin, board, free, open, source, smf, simple, machines, forum
)[/code]

[b]EDIT[/b] Updated code to get each attribute into an array.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.