Here are some examples to filter through strings in PHP to meet conditions.
PHP functions used during this tutorial are: substr, is_numeric, preg_replace, str_replace and trim.
Assume possible strings could be $string = "2 x Milky treat";
or $string = "Hash brown";
or $string = "-1 Fruit toast";
Here we have a trend that if it’s just one item there is no count x (2 x Milky treat), it’s just the item (Hash brown). Return or loss of item is seen as – count (-1 Fruit toast).
To get only strings that contain single items:
if (substr($string, 0, 1) == '-' || is_numeric(substr($string, 0, 1) == true){ //first character in string is either a - or a number } else { echo $string; }
Get string that has the negative:
if (substr($string, 0, 1) == '-'){ echo $string; } else { //first character is not a - }
Return the count of items strings only
if (is_numeric(substr($string, 0, 1)) !== FALSE) { echo $string; } else { //first character is not a number }
Get the count of items where count is greater than 5:
if (is_numeric(substr($string, 0, 1)) !== FALSE) { if (substr($string, 0, 1) > 5) { echo $string; } else { //first number is less than 5 } }
Return just the items:
if (is_numeric(substr($string, 0, 1)) !== FALSE || substr($string, 0, 1) == '-') { $words = preg_replace('/[0-9]+/', '', $string);//removes numbers 0-9 $words = str_replace('x', '', $words);//removes the x $words = str_replace('-', '', $words);//removes the - echo trim($words);//trim gets rid of whitespace at start and end (not during) } else { echo trim($string); }