首页 > 解决方案 > preg_match 函数不适用于 if 语句?

问题描述

我正在尝试对保存在数组元素中的字符串使用函数 pre_match $lines[$i]

字符串就像“关键字:南极洲;Landsat-8;ASTER;区域地质测绘;维多利亚北部土地”。

尽管该字符串包含 /Keywords/,但程序始终会转到 else 部分并显示“不在此处”。

任何帮助这是为什么?

提前致谢

$lines = file('C:\Tamer\Open Polar\New Keywords\Original citations files\combined.txt');
// Loop through our array

$length = count($lines);
for ($i = 0; $i <= $length; $i++) {

    settype($lines[$i], "string");              // Be sure that everything is string

    if(preg_match("/Keywords:/",$lines[$i]))
        {
            echo "we got it" . "<br />\n";
            }
        else
            {
            echo "not here" . "<br />\n";
            }
        }

标签: phpfindword

解决方案


使用 strpos/stripos php.net,因为无论如何它更快。

Settype 是不必要的,因为文件将被解析为字符串。

$lines = file('C:\Tamer\Open Polar\New Keywords\Original citations files\combined.txt');

$length = count($lines);
for ($i = 0; $i < $length; $i++) 
{
    if(strpos($lines[$i], 'Keywords:') !== false)
    {
         echo "we got it" . "<br />\n";
    }
    else
    {
        echo "not here" . "<br />\n";
    }
}

推荐阅读