How to extract data from a string in PHP?

Hello,

I have a string:

$str="Jim has 3 APPLES:";

OR

$str="Mrs Jones bought 6 ORANGES:";

I need to extract:
$name1 = "Jim" OR "Mrs Jones"
$name2 = "APPLES" or "ORANGES"
$number = "3" or "6"

name1 can be of 1 word or 2 words. name 2 is always 1 word in capital letters.

In PHP, how can I do the above?

Please help...

Thanks.

Jong

ccjongAsked:
Who is Participating?
 
peyoxConnect With a Mentor Commented:
This is a good one :)

<?
   $str = "Jim has 3 APPLES";
   $str = "Mrs Jones bought 6 ORANGES";

   $words = explode (" ", $str);

   for ($i=0; $i<sizeof($words); $i++)
   {
      if (strtoupper($words[$i])==$words[$i]) $name2 = $words[$i];
      if (is_numeric ($words[$i])) $number = $words[$i];
   }

   $name1=$words[0];

   if ($words[0]=="Mr" || $words[0]=="Mrs" || $words[0]=="Miss" || $words[0]=="Ms")
      $name1 .= " ".$words[1];

   // display result

   echo "name1: ".$name1."<br>";
   echo "name2: ".$name2."<br>";
   echo "number: ".$number."<br>";
?>
0
 
ccjongAuthor Commented:
Thanks peyox.

I modified a little and it works perfactly.

Jong
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.