Gre*_*ich 3 php regex fopen string-comparison
我们正在尝试显示文件是否包含特定字符串:
这里我们读取文件:
$myFile = "filename.txt";
$fh = fopen($myFile,'r');
$theData = fread($fh, filesize("filename.txt"));
fclose($fh);
Run Code Online (Sandbox Code Playgroud)
文件名.txt 包含“离线”
这里我们尝试比较字符串:
if(strcmp($theData,"Online")==0){
echo "Online"; }
elseif(strcmp($theData,"Offline")==0) {
echo "Offline"; }
else {
echo "This IF is not working." }
Run Code Online (Sandbox Code Playgroud)
我们尝试过使用常规 if 而不使用 strcomp,但它也不起作用。我认为 IF 无法将 fread 的结果与常规字符串进行比较。也许我们需要尝试另一种方法。
有任何想法吗?
使用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.";
}
Run Code Online (Sandbox Code Playgroud)
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'";
}
Run Code Online (Sandbox Code Playgroud)