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





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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.