Jump to content

Parse a string with PHP


Sneo

Recommended Posts

Hey,

Just a quick question on something I can't figure out to do with PHP! :P

 

Case 1:
$text = "You worked at the local bar and made $1456 for the night";

Case 2:
$text2 = "You worked at the local shop and made $5831 for the day";

 

Im looking for the following result:

Case 1:
$worked = "bar";
$wage = "$1456";

Case 2:
$worked = "shop";
$wage = "$5831";

 

Could someone help me out here? :)

Link to comment
Share on other sites

<pre>
<?php

$text = array(
	"You worked at the local bar and made $1456 for the night",
	"You worked at the local shop and made $5831 for the day"
);

foreach ($text as $piece) {
	preg_match('/(?<=local)\s+(\S+)[^$]+(\$\d+)/', $piece, $matches);
	array_shift($matches);
	print_r($matches);
}

?>
</pre>

Link to comment
Share on other sites

just use The Little Guy's code and change it slightly

 

<?php
$text = "You worked at the local bar and made $1456 for the night";

if(preg_match("/made.+for/",$text,$matches)){
echo $matches[0];
}else{
echo 'nothing found';
}
?>

 

I think that should work ;D

 

~ Chocopi

Link to comment
Share on other sites

there may be a better way, but this works for me:

 

<?php
$text = "You worked at the local bar and made $1456 for the night";

if(preg_match("/local.+for/",$text,$matches)){
list($unsed,$worked,$unused,$unsed,$wage) = explode(" ",$matches[0]);
echo $worked.'<br>'.$wage;
}else{
echo 'nothing found';
}
?>

 

this will not work, if "bar" is changed to something containing 2+ words, like "super market"

Link to comment
Share on other sites

Mmm.. Looks good! I have to change the variables to an array? It would be easier for me to keep them as variables..

 

No, you don't have to change them to an array; effigy just did that in order to loop through the two options.  The important part of the code is the preg_match bit.

 

preg_match('/worked at the local (.*?) and made (\$\d+)/i', $text, $matched);
echo $matched[1];
echo $matched[2];

 

The regular expression can be as general or as specific as you need.

Link to comment
Share on other sites

Not a fan of that, as it isn't just based around this one text string.. There is a few, basically I'm going to be able to Post these "Earns".

 

The real example would be:

[Note: Only one would be posted at a time]

Case 1:

You walked the beat for ages today - protecting the citizens of Paris and earned yourself a $91 bonus! No taxes were taken as Paris has no mayor.

 

Case 2:

You scammed some poor suckers into your scam - they invested their last $2714 and bought some of your phoney stocks!

 

I need the script to figure out which Earn I have done. Bearing in mind, the last part: "No taxes were taken as Paris has no mayor." can change as well as the amount of money made. I then need it to fetch how much I made from that Earn and store it as a variable. Sorry I didn't explain this clearer earlier, didn't realise it would be so complex! :P

 

 

Link to comment
Share on other sites

OK... Here are two simple long functions

 

split_string();

and

return_between();

(scroll to bottom of box to see functions working)

<?php
function split_string($string, $delineator, $desired, $type)
    {
    # Case insensitive parse, convert string and delineator to lower case
    $lc_str = strtolower($string);
$marker = strtolower($delineator);
    
    # Return text BEFORE the delineator
    if($desired == BEFORE)
        {
        if($type == EXCL)  // Return text ESCL of the delineator
            $split_here = strpos($lc_str, $marker);
        else               // Return text INCL of the delineator
            $split_here = strpos($lc_str, $marker)+strlen($marker);
        
        $parsed_string = substr($string, 0, $split_here);
        }
    # Return text AFTER the delineator
    else
        {
        if($type==EXCL)    // Return text ESCL of the delineator
            $split_here = strpos($lc_str, $marker) + strlen($marker);
        else               // Return text INCL of the delineator
            $split_here = strpos($lc_str, $marker) ;
        
        $parsed_string =  substr($string, $split_here, strlen($string));
        }
    return $parsed_string;
    }
    
    
function return_between($string, $start, $stop, $type)
    {
    $temp = split_string($string, $start, AFTER, $type);
    return split_string($temp, $stop, BEFORE, $type);
    }
    
    
$text = "You worked at the local bar and made $1456 for the night";
    $worked = return_between($text,"local","and",EXCL);
    $wage = return_between($text,"made","for",EXCL);
    echo $worked.'<br>'.$wage;
?>

 

use the return_between function to return anything between two values (text or html).

- the first value is the full text string

- the second value is the first thing to look for

- the third value is the last next thing to look for

- the fourth value is the weather to include or exclude the value from the returned result

 

if this doesn't make sense ask what you have a question about.

Link to comment
Share on other sites

I need the script to figure out which Earn I have done. Bearing in mind, the last part: "No taxes were taken as Paris has no mayor." can change as well as the amount of money made. I then need it to fetch how much I made from that Earn and store it as a variable. Sorry I didn't explain this clearer earlier, didn't realise it would be so complex! :P

 

Well, the original examples were very similar, so a regular expression was easy to write.  If you are trying to match natural language, good freaking luck.  :)

 

Dollar amounts won't be hard to find as they are always preceeded by a "$", but pulling the noun and verb out of the beginning action might be harder.  If they're always past tense, you could use /You (\w+ed).+?(\$[0-9.,])/i so you would return "walked" & "$91" in the first sentence and "scammed" and "$2714" in the second.

 

What are you doing, writing a script to play an RPG?

Link to comment
Share on other sites

Not a fan of that, as it isn't just based around this one text string.. There is a few, basically I'm going to be able to Post these "Earns".

 

The real example would be:

[Note: Only one would be posted at a time]

Case 1:

You walked the beat for ages today - protecting the citizens of Paris and earned yourself a $91 bonus! No taxes were taken as Paris has no mayor.

 

Case 2:

You scammed some poor suckers into your scam - they invested their last $2714 and bought some of your phoney stocks!

 

I need the script to figure out which Earn I have done. Bearing in mind, the last part: "No taxes were taken as Paris has no mayor." can change as well as the amount of money made. I then need it to fetch how much I made from that Earn and store it as a variable. Sorry I didn't explain this clearer earlier, didn't realise it would be so complex! :P

 

 

 

That can be very complex. The money part is the easy part to determine.

 

<?php
function get_money($string) {
     list($first,$second) = split('$', $test);
     list($money) = split(' ', $test);
     return '$' . $money;
}

$string = "I made $1,065 in 1 days worth of work!";
echo get_money($string);
?>

 

The other part is more work as I can easily say, "You bought $50 worth of stock and lost 10% after earning $100" I am not sure if you get that complex, but the human language is hard to interpret. Because you can have earn in a statement and not actually earned money, "You earned $100 after an initial 10% loss" etc.

 

My suggestion is if you have a list of what you know will be there is store this into an array and have it assigned what it means. Anyways hope this helps you out.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.