Forum Moderators: coopster

Message Too Old, No Replies

Adapting a piece of code with array and foreach

array foreach,

         

hanyaz

10:34 am on Sep 30, 2008 (gmt 0)

10+ Year Member



Hello,
I have script gathering the title and the metatags from a given url. However this piece of code applies only for One url. I tried to make an array and use foreach but no success. Here is the original code :
<?php
$page_title = "n/a";
$meta_descr = "n/a";
$meta_keywd = "n/a";

if ($handle = @fopen("http://mywebsite.com", "r")) {
$content = "";
while (!feof($handle)) {
$part = fread($handle, 1024);
$content .= $part;
if (eregi("</head>", $part)) break;
}
fclose($handle);
$lines = preg_split("/\r?\nŠ\r/", $content); // turn the content in rows
$is_title = false;
$is_descr = false;
$is_keywd = false;
$close_tag = ($xhtml) ? " />" : ">"; // new in ver. 1.01
foreach ($lines as $val) {
if (eregi("<title>(.*)</title>", $val, $title)) {
$page_title = $title[1];
$is_title = true;
}
if (eregi("<meta name=\"description\" content=\"(.*)\"([[:space:]]?/)?>", $val, $descr)) {
$meta_descr = $descr[1];
$is_descr = true;
}
if (eregi("<meta name=\"keywords\" content=\"(.*)\"([[:space:]]?/)?>", $val, $keywd)) {
$meta_keywd = $keywd[1];
$is_keywd = true;
}
if ($is_title && $is_descr && $is_keywd) break;
}
}

/*foreach ( $TESTURL as $url )
{
*/
echo $page_title;
echo "<br>";
echo $meta_descr;

/*}*/
?>

andrewsmd

11:36 am on Sep 30, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This may not be the correct answer but to do a preg split I believe you have to start your regex with ^ and end it with a $ (^/\r?\nŠ\r/$), at least that's how I've always done them. Usually when you do those kinds of things it's better to assign a variable like $expression as your regex.