Comparing string in php

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 do not know what position it is in.

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

This code is within a While and the purpose is to go line by line to count how many times the IDLE tag appears.     

asked by anonymous 17.06.2014 / 19:08

2 answers

3

I do not know exactly where your $linha comes from but I see two options. Or compares how you are doing, and it only gives true if $linha has exactly the 'idle' characters;

or search the sequence of letters with a RegEx.

But beware: Your variable $ch_atend should be assigned 0 out of 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++; };
    
17.06.2014 / 19:22
4

PHP already has a function ready to count occurrences of substrings in strings, substr_count . With this, the line-by-line loop is neither necessary. The usage is like this:

$texto = "um texto grande ... \n multilinha ... \n sei lá mais o que ...";
$ocorrencias = substr_count($texto, '...');
echo $ocorrencias; // 3
    
17.06.2014 / 19:23