Jump to content

[SOLVED] Need some quick help extracting data from a string


moola

Recommended Posts

Test Location:  United States - South Carolina - Greenville - Bellsouth.net In


I need to grab the following Greenville and South Carolina from the exact format of the string above..
I am using the fget function to get the string from a website into an $buffer

$buffer .= fgets($fd, 4096);

Basically i need to extract South Carolina and put it into $state
And Greenville and put it into $city
other variables would be cool but not necessary.
This may be a bit of an easy question but I really got no time to master regex's right not I would love to learn it soon. I'm new to php still learning some other stuff before i get to everyone favorite lol





Link to comment
Share on other sites

If the string is always in that format:

[code]
<?php
  $buffer = "United States - South Carolina - Greenville - Bellsouth.net In";

  preg_match_all('/(.*)\s-\s(.*)\s-\s(.*)\s-\s(.*)/',$buffer,$matches,PREG_PATTERN_ORDER);

  $state = $matches[2][0];
  $city = $matches[3][0];

  //use this code below to see the values and structure of the $matches array.  You could set other variables using the same format above.
  echo "MATCHES:<pre>".print_r($matches,TRUE)."</pre>";
?>

[/code]
Link to comment
Share on other sites

Use explode()

ex
[hr]
[code=php:0]$str = "Test Location:  United States - South Carolina - Greenville - Bellsouth.net In";
list( , $state, $city) = explode(' - ', $str);[/code]
[hr]

Now the state is stored in [b]$state[/b], and the city in [b]$city[/b] ;)
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.