user2089120
user2089120

Reputation: 195

PHP strpos() finds just single characters, not a whole string

I have a strange problem...

I would like to search in a logfile.

$lines = file($file);

$sampleName = "T3173sGas";

foreach ($lines as &$line) {

if (strpos($line, $sampleName) !== false) {
echo "yes";
  }
}

This code is not working, $sampleName is to 100% in the log file. The search works just for single characters; for example "T" or "3" but not for "T3".

Do you have an idea why it's not working? Is the encoding of the logfile wrong?

Thanks a lot for your help!

Upvotes: 1

Views: 932

Answers (2)

alexbaeck
alexbaeck

Reputation: 1

This may work, it searches for the entire string

<?php
$filename = 'test.php';
$file = file_get_contents($filename);
$sampleName = "T3173sGas";
if(strlen(strstr($file,$sampleName))>0)
{
echo "yes"; 
}
?>

Upvotes: 0

M8R-1jmw5r
M8R-1jmw5r

Reputation: 5006

If you can only find single characters I would assume that your logfile is in some multi-byte character set like UTF-16. As you already assume similar, next step for you is to consult the documentation / specification of the logfile you're trying to operate with regarding the character encoding.

You then can use character-encoding specific string functions, the package is called http://php.net/mbstring.

$encoding = ... ; // encoding of logfile

if (mb_strpos($line, $sampleName, 0, $encoding) !== false) {
    echo "yes";
}

Upvotes: 2

Related Questions