How to extract data from a string in PHP?

Posted on 2005-04-11
Last Modified: 2008-01-09

I have a string:

$str="Jim has 3 APPLES:";


$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...



Question by:ccjong
    LVL 6

    Accepted Solution

    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];


       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>";

    Author Comment

    Thanks peyox.

    I modified a little and it works perfactly.


    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now