Jump to content

Only return the first instance of "X"


soma56

Recommended Posts

Ok, so I've figured out how to parse and bring back content from within <title> and </title> tags.

 

However I'm having a heck of a time trying to figure out how to grab the contents between

 

<meta name="keywords" content="grab-this-content" />

 

My program seems to grab everything that ends with "/>". The keywords, in addition to several other elements that I don't need. The only thing I want is between:

 

<meta name="keywords" content="

 

and the first instance of

 

/>

 

Does anyone understand what I'm trying to do? Can you please give me some direction?

 

Link to comment
Share on other sites

~<meta name="keywords" content="([^"]+)~

 

$str = '<meta name="keywords" content="grab-this-content" />';
preg_match('~<meta name="keywords" content="([^"]+)~', $str, $matches);
print_r($matches);

Link to comment
Share on other sites

Actually - in this case you may find using the DOM and XPath a better method - preg_match is expensive and slow...

 

something like:

$doc = new DOMDocument();
$doc->loadHTMLFile("/path/to/your/file.html");
$xpath = new DOMXpath($doc);

 

then you can grab all manner of info without having to run preg_match over and over again..

 

$title = $xpath->query("//title")->item( 0 )->nodeValue;
$keywords = $xpath->query("//meta[@name='keywords']")->item(0)->getAttribute('content');

 

and so on and so forth...

 

You should find this method a bit more efficient/quicker and a bit more fun ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.