Comparing string in php

Asked

Viewed 1,628 times

4

I would like to know how to compare the contents of a string in PHP.
I’m looking for a word on a line, but I don’t know what position she’s in.

$ch_atend
if($linha == "idle") { $ch_atend = $ch_atend++; };

That code is inside a While and the purpose is to go line by line to count how many times the word appears IDLE.

2 answers

4

PHP already has a function ready to count substring occurrences in a string, substr_count. With this, the loop line by line is not even necessary. The use is like this:

$texto = "um texto grande ... \n multilinha ... \n sei lá mais o que ...";
$ocorrencias = substr_count($texto, '...');
echo $ocorrencias; // 3
  • Good morning. <br/> I tried this way and returned 0 and the file has an Idle word. <br> '<? php $file = fopen("agents.txt", "r"); if($file == false) { print "Could not open the file"; } $ch_atend = 0; while(true) { $line = fgets($file); if($line==NULL) { break; } echo $line." <br />"; } $cont_idle = substr_count($line, "Idle"); echo $cont_idle; fclose($file); ?>

  • At the moment you are checking, the line is null. Move the check inside the loop, or check the entire file at once.

  • I figured it was Null, just didn’t know what to do. Thanks.

3


I don’t know exactly where yours comes from $linha but I see two options. Or compare how you’re doing, and then it only comes true if $linha has exactly the characters `Idle``;

or find the sequence of letters with a Regex.

But even: your variable $ch_atend should be assigned 0 outside the while.

Option 1:

$ch_atend = 0;
while(<condição>){
    if($linha == "idle") { $ch_atend = $ch_atend++; };

Option 2

$ch_atend = 0;
while(<condição>){
    if(preg_match('/idle/', $linha )) { $ch_atend = $ch_atend++; };
  • stripos instead of regular expression would also serve.

  • Option 1 is exactly what I had put, as you can see in the opening of the question. Option 2 I tested the same way and it didn’t work. Both texts are in minuscule and returns zero. I don’t know what to do. Thanks.

  • I tested only with substr_count and another file and it worked normally. From what I understand, the variable $line is always passing zero. I need help.

  • I’m alone in the forum. I got it with preg_match. For some reason, it didn’t work with $ch_atend = $ch_atend++ $ch_atend = $atend + 1;

  • Sérgio. My $line is the variable that runs along the line of a text file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.