I have a table in a string where the string could contain this string ($table_data
):
<table>
<tr class="rowset-1"><td>cell1</td></tr>
<tr class="rowset-2"><td>cell1</td></tr>
<tr class="rowset-3"><td>cell1</td></tr>
</table>
From this string I want to count how many rows there are in the table. I do count number of rows like this:
$i = 1;
while( true )
{
if (strpos( $table_data, 'rowset-'.$i ) === false )
{
$nr_rows = $i - 1;
break;
}
$i++;
}
What I'm doing is simply to look for the class rowset-X were x is a number starting with 1. If it does not exist I have counted number of rows... (In above case 3 rows)
I'm looking for a way just to get largest number of rowset-? in a string (where ? is the largest number) with a better approach (My gut feeling is that my current approach is absolutely not the best).
My Answer:
php
$table_data = "substring-1, substring-2, substring-3, substring-1, substring-4, substring-1";
$sub_string = "substring-";
$count_array = array_count_values(array_filter(explode(", ", $table_data)));
$max_count = 0;
foreach ($count_array as $key => $value) {
if (strpos($key, $sub_string) === 0) {
$max_count = max($max_count, $value);
}
}
echo "Max count of substring- occurrences: " . $max_count;
Rate this post
3 of 5 based on 9897 votesComments