简体   繁体   中英

How can I count the amount of equal signs in a line in php

I need to count the number of equal signs in a line. What is the best way of doing this. The text file is also pretty large, so if possible I would first like to check to see if an equal sign is in the line at all and then count them (if this would be faster). I do not need to know how to loop through the lines (I already know this part). Also if there is a way to do it so if it hits a certain number (for instance if more than 5 equal signs are in the line) that would would automatically stop (if this speeds things up).

Regards,

Use substr_count. It returns the number of substring occurences in a line.

For example:

$count = substr_count( $line, '=' );

As for counting occurrences, just use substr_count() .

Assuming you know how to buffer input the file (rather than trying to load it all into memory at once), you pretty much have to start at the beginning to do a correct line count either to filter to a particular range of line numbers or simply to identify the line number. Lines are variable length after all.

This uses preg_match_all() for each line. Is that what you are looking for?

$fil = file("listcontent.php");
foreach ( $fil as $line ) {
    $matches = array();
    $count = preg_match_all("/(=[^=]*)/",$line,$matches);
    if ( $count ) echo $count.": ".$line;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM