简体   繁体   中英

PHP preg_match between tags with PHP logic inside

I have a dynamic sitemap creation script that recursively looks through the filesystem and when needed, opens the start of a file, then looks for the text between tags. It worked when the setup was like...

<title>Page Title | Company, Inc.</title>

But now I've added a wrinkle and set up a way to manage titles and meta info via an admin tool. Just in case something isn't entered, I want to fall back to the old default title info, but my preg_match isn't working for this...

<title><?=@$page_meta_array['page_title']!=''?$page_meta_array['page_title']:"Default Title Here";?> | Company, Inc.</title>

The php function that I pass the page to looks like this...

function get_title($filename) {
    $retval = "";
    $handle = fopen($filename, "r");
    $head = fread($handle, 4096);
    preg_match(";<title>(.+)</title>;", $head, $matches);
    if(sizeof($matches) == 2) {
        $retval = trim($matches[1]);
    }
    fclose($handle);

    return $retval;
}

Can someone point me to the correct preg_match? I'd like to have "Default Title Here" returned from the second example above.

Thanks

this might do it:

preg_match(';<title><\?[^>]*"([^"]*)"[^>]*></title>;', $head, $matches);

note that short-tags are deprecated, and may not work in PHP6.

you first need to parse the PHP code, then check for matches. Why don't you just use the contents of $page_meta_array['page_title']?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM