PHP字符串比较。正则表达式

3
我们尝试展示一个文件是否包含特定的字符串:

在这里我们读取文件:

$myFile = "filename.txt";
$fh = fopen($myFile,'r');
$theData = fread($fh, filesize("filename.txt"));
fclose($fh);

filename.txt 包含 "Offline"。

这里我们正在尝试比较字符串:

if(strcmp($theData,"Online")==0){
echo "Online"; }
elseif(strcmp($theData,"Offline")==0) {
echo "Offline"; }
else {
echo "This IF is not working." }

我们尝试过使用普通if语句而不是strcomp,但它也没有起作用。我认为IF无法将fread的结果与普通字符串进行比较。也许我们需要尝试另一种方法。
有什么想法吗?

尝试对$theData进行var_dump()以了解其类型并获取更多信息。 - Hoijof
你尝试过 var_dump($theData) 吗? - hjpotter92
4个回答

5

使用preg_match()

$string = "your-string";
$pattern = "/\boffline\b/i"; 

// The \b in the pattern indicates a word boundary, so only the distinct 
// word "offline" is matched; if you want to match even partial word "offline"
// within some word, change the pattern to this /offline/i

if(preg_match($pattern, $string)) {
    echo "A match was found.";
}

您也可以使用 strpos()(在这种情况下它更快)

$string = 'your-stringoffline';
$find   = 'offline';
$pos = strpos($string, $find);

if($pos !== false){
    echo "The string '$find' was found in the string '$string' at position $pos";
}else{
    echo "The string '$find' was not found in the string '$string'";
}

0

当在长字符串中搜索时,正则表达式非常慢。请使用strpos。

$strFile = file_get_contents("filename.txt"); // load file
if(strpos($strFile, 'Online')!==false){ // check if "Online" exists
    echo "We are Online";
    }
elseif(strpos($strFile, 'Offline')!==false){ // check if "Offline" exists
    echo "We are Offline";
    }
else{ // other cases
    echo "Status is unknown";
    }

0

我提供了另一种方法来完成这个(取决于文件内部的内容),虽然它不是最好的,但在某些情况下可能会有用。

if (exec("grep Offline filename.txt") === 'Offline')
    echo 'Offline';
else
    echo 'Online';

再见


-1
你检查了 $theData 中是否包含该值吗?
可以尝试以下代码:
if(strcmp($theData,"Online") === 0)
   echo $theData." is equal to string Online using case sensisive"; 
else if(strcmp($theData,"Offline") === 0)
   echo $theData." is equal to string Offline using case sensisive"; 
else
   echo $theData." This IF is not working.";  

这里是更多信息的文档:http://php.net//manual/zh/function.strcmp.php

或者使用hex494M49的方法:(未经测试)

function isStringAreTheSame($initialString, $stringToCompare) {
   $pattern = "/\b".$initialString."\b/";

   return preg_match($pattern, $stringToCompare);
}

1
$pattern = "/\b".$initialString."\b/" or you'll get Warning: preg_match(): No ending delimiter '/' found in... - Scott Fleming
我已经根据您的建议更新了我的帖子 ;) 谢谢您;) - Lapinou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接