strpos() >0 与在字符串开头找到的针不匹配[重复]

问题描述 投票:0回答:1

我编写了一个简短的小函数来读取 CSS 文件并返回属性的值。问题是它读取了我想要的值,然后将错误的值进一步返回到文件中。

这是函数;

function get_css($f, $tag, $el) {
$css = fopen($f, "r");
$line = fgets($css);
while ( !feof($css) ) {
    if(strpos($line, $tag) > 0) {
        while ( !feof($css) ) {
            $line = fgets($css);
            if (strpos($line, $el) > 0) {
                return substr(substr($line, strpos($line, ":")+1), 0, -1);
            }
        }
    }
    $line = fgets($css);
}
}

我是这样称呼它的;

$ew = get_css("1688_style.css", "elevations", "width");

这是它正在读取的 CSS 文件的示例;

Body {
margin:0;
color:black;
width:100%;
height:100%;
margin-left:auto;
margin-right:auto;
padding:0px;
font-family:arial,sans-serif;
background-color:#FFFFFF;
}

#Content {
position:relative;
display:inline-block;
background-color:#FFFFFF;
margin-top:30px;
margin-left:80px;
width:1520px;
}

#elevations {
position:relative;
display:inline-block;
width:250px;
text-align:center;
}                   

#views {
 display:inline-block;
 cursor:pointer;
 margin-top:20px;
 margin-left:15px;
}

#help {
 position:absolute;
 width:50px;
 text-align:center;
 font-size:12px;
 top:18px;
 right:20px;
}

我期望的是 250px,但我从 #help 标签得到的是 50px。我已经不知道要在这里尝试什么了。

php strpos
1个回答
3
投票
如果搜索字符串位于内容的开头,则

strpos
将返回 0;如果根本不存在,则返回
false
。所以...

if(strpos($line,$tag) > 0)

应该是...

if(strpos($line,$tag) !== false)

您使用

strpos
的其他地方也是如此,最后您可以删除
+1
,因为不需要它。

© www.soinside.com 2019 - 2024. All rights reserved.