shopp('product','quantity','input=menu&return=true');
The above function from my CMS returns the value <select name="products[1][quantity]" id="quantity-1"><option selected="selected" value="1">1</option><option value="2">2</option><option value="3">3</option></select>.
Any idea how I can get the number in that last option tag and assign it to a variable in php? In the above case, I’d like to assign the number ‘3’ to a variable, say, $aaa.
(BTW, the number of option tags is not fixed, and can go up to a few hundred.)
Update:
Oh boy, sometimes it is even easier than one thinks. There is already a function that counts substrings:
substr_count().So now it is just:
So if you say it could be a few hundred option tags, this solution is much better as it does not generate intermediate arrays.
Old answer: (is doing the same in a more complicated way)
Here is another hacky way:
The HTML string represents a select box that lets you select quantities. Thus, we can assume that the number of
optiontags represent the maximum number to choose from (in your example3).So we only have to count the number of option tags. We can do this using a combination of
str_word_count()andarray_count_values().So assuming we have this HTML string (from your example):
we can get the words be using
str_word_count(). As there are opening and closingoptiontags, we are looking for closing tags for simplicity. Hence we have to tell the function to treat/also as word character:gives:
As we can see
/optionoccurs 3 times.Now we use
array_count_values()to count them:gives:
So we can get the number of
optiontags and therefore the highest number by simply applying:Of course using a HTML parser would be better, but if you know that the function will always generate the HTML this way, counting the option tags should work.