简体   繁体   中英

What is wrong with my Regex Function?

It seems like such a simple matter. Anyways, at the bottom of my code is an array which uses the outcome of the function. Now it doesn't seem to be working and i think it might be my regex for scanning Meta Keywords. So basically, I want to know what my function is doing wrong or how to create a fully working regex code

function getKeywords($link) {
$str2 = file_get_contents($link);    
if (strlen($str2)>0) {
    preg_match_all( '(?i)<meta\\s+name=\"keywords\"\\s+content=\"(.*?)\">', $str2, $keywords);
  return $keywords[1];
}
}

try this:

function getKeywords($link) {
    $str2 = file_get_contents($link);    
    if (strlen($str2)>0) {
        if(preg_match( '/<meta\s+name="keywords"\s+content="(.*?)">/i', $str2, $keywords))
            return $keywords[1];
        else
            return "";

    }
}

You had multiple problems with your expression:

1). To many escape chars for \\s and \\"

2). You didn't lead with a / and end with a /

3). You were using preg_match_all instead of preg_match

4). You didn't handle the case when no keyword meta tag can be found.

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