I have a line of code in my wordpress widget that outputs from an RSS feed:
<?php echo $entry->title ?>
and when displayed it looks like:
$220,000 :: 504 Freemason St, Unit 2B, Norfolk VA, 23510
or
$274,900 :: 1268 Bells Road, Virginia Beach VA, 23454
What is the easiest way to break this up into different objects?
For example, I'd like to have the price, street name, and city state zip in different objects. The problem is that some of the addresses have unit numbers and it's complicating things. Below is an example of how I would like it to work:
<?php echo $entry->price ?>
<?php echo $entry->street ?>
<?php echo $entry->citystatezip ?>
$220,000
504 Freemason St, Unit 2B
Norfolk VA, 23510
or
$274,900
1268 Bells Road
Virginia Beach VA, 23454
Here is a very crude regex that seems able to parse your string. I'm not the best with regexes, but it seems to work.
/^(\$(?:\d{1,3},?)*) :: (\d* [\w\s,\d]*), ([\w\s]* \w{2}, \d{5})$/
Use this with preg_match; the 1st group is the price, the 2nd is the address, and 3rd is the city/state/zip.
Example:
<?php
$ptn = '/^(\$(?:\d{1,3},?)*) :: (\d* [\w\s,\d]*), ([\w\s]* \w{2}, \d{5})$/';
if(preg_match($ptn, $entry->title, $match) === 1){
$price = $match[1];
$street = $match[2];
$citystatezip = $match[3];
}
What you need is a regular expression , check http://php.net/manual/en/function.preg-match.php
Use f.e. array explode ( string $delimiter , string $string [, int $limit ] ) which will give you array with strings if you use correct delimiter
The code below will fill your $entry object as required:
$string = '$274,900 :: 1268 Bells Road, Virginia Beach VA, 23454';
$pricePart = explode('::', $string);
$addressPart = explode(',', $pricePart[1]);
$entry = new stdClass();
$entry->price = trim($pricePart[0]);
if ( count($addressPart) == 3 ) {
$entry->street = trim($addressPart[0]);
$entry->citystatezip = trim($addressPart[1]) . ', ' . trim($addressPart[2]);
} else {
$entry->street = trim($addressPart[0]) . ', ' . trim($addressPart[1]);
$entry->citystatezip = trim($addressPart[2]) . ', ' . trim($addressPart[3]);
}
Updated answer to handle the unit bit
Update: changed array names, I hate $array.. names.. even if its just a mockup
(Note: this code isn't the prettiest, but its ment to give a base to work on. It should be cleaned up and improved a bit)
Related
Lets say, this is my address 537 Great North Road Grey Lynn Auckland City Auckland.
I want to put comma (,) after Grey Lynn and Auckland City
Then address will 537 Great North Road, Grey Lynn, Auckland City, Auckland
How can I do it in PHP? When the length is not fixed.
This is not a perfect solution but you can get an idea how you deal with it.
By using PHP :
$t = "537 Great North Road Grey Lynn Auckland City Auckland";
$t = str_replace(
["Road", "Lynn", "City"], // neddle
["Road,", "Lynn,", "City,"], // replace
$t
);
echo $t;
More Details
I would suggest you look at Regular Expressions (RegEx) to achieve this.
In that way you could loop through each address and use the regex pattern to replace where a comma is required.
However, I believe due to the format of the data it might be very hard to actually achieve this. The only thing you have to detect where a comma needs to go is a space, and that isn't reliable as you can have spaces between road names etc where you don't want commas to be placed!
If you can I would suggest splitting the data up, so rather than having the address in one string you have it split in separate columns / variables, for "house number", "street", "town" etc.. That way you could then use a simple string concatenation to place the commas where they should go.
E.g.:
$houseNumber . " " . $street . ", " . $town . ",";
I hope that helps!
Try This Before and after variable you can put comma.
<?php
$GreyLynn = "Grey Lynn";
$AucklandCity = "Auckland City";
echo ' , '.$GreyLynn.' , '.$AucklandCity;
?>
$seperate = "537 Great North Road Grey Lynn Auckland City Auckland";
$replace = str_replace ("Grey Lynn", ",Grey Lynn, ",$seperate);
$location = str_replace `("Auckland City", "Auckland City, ",$replace);`
Result:
537 Great North Road ,Grey Lynn, Auckland City, Auckland
I have a field which contain 20 character (pad string with space character from right) like below:
VINEYARD HAVEN MA
BOLIVAR TN
,
BOLIVAR, TN
NORTH TONAWANDA, NY
How can I use regular expression to parse and get data, the result I want will look like this:
[1] VINEYARD HAVEN [2] MA
[1] BOLIVAR [2] TN
[1] , or empty [2] , or empty
[1] BOLIVAR, or BOLIVAR [2] TN or ,TN
[1] NORTH TONAWANDA, or NORTH TONAWANDA [2] NY or ,NY
Currently I use this regex:
^(\D*)(?=[ ]\w{2}[ ]*)([ ]\w{2}[ ]*)
But it couldnot match the line:
,
Please help to adjust my regex so that I match all data above
What about this regex: ^(.*)[ ,](\w*)$ ? You can see working it here: http://regexr.com/3cno7.
Example usage:
<?php
$string = 'VINEYARD HAVEN MA
BOLIVAR TN
,
BOLIVAR, TN
NORTH TONAWANDA, NY';
$lines = array_map('trim', explode("\n", $string));
$pattern = '/^(.*)[ ,](\w*)$/';
foreach ($lines as $line) {
$res = preg_match($pattern, $line, $matched);
print 'first: "' . $matched[1] . '", second: "' . $matched[2] . '"' . PHP_EOL;
}
It's probably possible to implement this in a regular expression (try /(.*)\b([A-Z][A-Z])$/ ), however if you don't know how to write the regular expression you'll never be able to debug it. Yes, its worth finding out as a learning exercise, but since we're talking about PHP here (which does have a mechanism for storing compiled REs and isn't often used for bulk data operations) I would use something like the following if I needed to solve the problem quickly and in maintainable code:
$str=trim($str);
if (preg_match("/\b[A-Z][A-Z]$/i", $str, $match)) {
$state=$match[0];
$town=trim(substr($str,0,-2)), " ,\t\n\r\0\x0B");
}
I am having one HTML form, where in the address to be entered in text box
and the PHP out produce the data with following php code as:
$address = $_POST["address"];
echo $address;
And the out put comes in a single line like:
The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268
But I need the out put in readable manner in 3-4 lines.
i.e for each "," break / new line to be made - so that the out put would be:
The Manager,
Scotia bank Ltd,
Cincinnati Finance Center,
26 W. Martin Luther King Raod,
Cincinnati,
Ohio 45268
Can any body help me getting the soluation please?
If the output is displayed in a textarea:
$address = str_replace(",",",\n",$_POST['address']);
echo $address;
If its on HTML:
$address = str_replace(",",",<br/>",$_POST['address']);
echo $address;
If , is the delimiter that you want to split the string then try with explode in php
$str = 'The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268';
$arr = explode(',',$str);
print_r($arr);
Check the manual for more
Explode is the function you are searching for..
$str = 'The string';
$arr = explode(',',$str);
print_r($arr);
Learn more about explode here.
Perhaps something like:
implode(",\n", explode(",", $string));
You can use explode.Try this :
<?php
$str= "The Manager, Scotia bank Ltd,Cincinnati Finance Center,26 W. Martin Luther King Road, Cincinnati, Ohio 45268";
$arr = explode(",",$str);
for($i=0;$i<count($arr);$i++)
{
if($i==(count($arr)-1))
$comma = "";
else
$comma = ",";
echo $arr[$i].$comma."<br>";
}
I'm successfully returning json from Wikipedia but am not having any luck grabbing the value I need in PHP (trying to do this in a Drupal site).
Here is the code I'm using, you can substitute $safeurl for this value:
Squantz%20Pond%20State%20Park
<?php
$safeurl = str_replace(' ', '%20', $title);
$json_string = file_get_contents("http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=" . $safeurl);
$parsed_json = json_decode($json_string, true);
$text = $parsed_json->{'extract'};
print "What I need:" . $text;
?>
If I print $json_string out in my HTML I see the following text which contains what I'm going after, the "extract" value. I just can't figure out what $text needs to be to grab that paragraph.
{"query":{"pages":{"1332160":{"pageid":1332160,"ns":0,"title":"Squantz Pond State Park","extract":"Squantz Pond State Park is a state park located 10 miles (16\u00a0km) north of Danbury in the town of New Fairfield, Connecticut. The park offers opportunities for swimming, fishing, hiking and boating.\n"}}}}
You need to change your json_decode to
$parsed_json = json_decode($json_string);
Since, you pass the true the $parsed_json will become an array. So remove the true flag.
and access it like ...
$text = $parsed_json->query->pages->{1332160}->extract;
What if 1332160 is not known ?
Proceed like this..
foreach($parsed_json->query->pages as $k)
{
echo $k->extract;
}
I am using following PHP code
<?
$data = file_get_contents('http://www.kitco.com/texten/texten.html');
preg_match_all('/([A-Z]{3,5}\s+[0-9]{1,2},[0-9]{4}\s+([0-9.NA]{2,10}\s+){1,7})/si',$data,$result);
$records = array();
foreach($result[1] as $date) {
$temp = preg_split('/\s+/',$date);
$index = array_shift($temp);
$index.= array_shift($temp);
$records[$index] = implode(',',$temp);
}
print_R($records);
?>
To READ the following data
--------------------------------------------------------------------------------
London Fix GOLD SILVER PLATINUM PALLADIUM
AM PM AM PM AM PM
--------------------------------------------------------------------------------
Jun 03,2013 1396.75 1402.50 22.4300 1466.00 1487.00 749.00 755.00
May 31,2013 1410.25 1394.50 22.5700 1471.00 1459.00 755.00 744.00
--------------------------------------------------------------------------------
What i want to do is Read GOLD ( BID & ASK ) price from below table, can anyone help in the regular expression changes?
New York Spot Price
MARKET IS CLOSED
Will open in
----------------------------------------------------------------------
Metals Bid Ask Change Low High
----------------------------------------------------------------------
Gold 1411.20 1412.20 +22.90 +1.65% 1390.10 1418.00
Silver 22.74 22.84 +0.48 +2.13% 22.26 23.08
Platinum 1495.00 1501.00 +41.00 +2.82% 1470.00 1511.00
Palladium 756.00 761.00 +7.00 +0.93% 750.00 766.00
----------------------------------------------------------------------
Last Update on Jun 03, 2013 at 17:14.58
----------------------------------------------------------------------
I'm not sure you could modify your existing regex to match both tables easily, but if you had the second table in a string, you could use:
$string = "PLAIN TEXT TABLE DATA HERE";
preg_match('/Gold\s+(\d+\.\d{2})\s+(\d+\.\d{2})/',$string,$matches);
$goldBid = $matches[1];
$goldAsk = $matches[2];
Here I'm only matching the numbers and period character. This code should return the numbers you're looking for. It uses your data string from your example.
<?
preg_match_all('!Gold\s+([0-9.]+)\s+([0-9.]+)!i',$data,$matches);
//New York
$ny_bid = $matches[1][0];
$ny_ask = $matches[2][0];
print("NY\nbid: $ny_bid\n");
print("ask: $ny_ask\n\n");
//Asia
$asia_bid = $matches[1][1];
$asia_ask = $matches[2][1];
print("Asia\nbid: $asia_bid\n");
print("ask: $asia_ask\n");
?>
Output
NY
bid: 1411.20
ask: 1412.20
Asia
bid: 1406.80
ask: 1407.80
You can also use T-Regx library
<?php
pattern('Gold\s+([0-9.]+)\s+([0-9.]+)', 'i')->match($data)->forEach(function ($m) {
print 'bid: ' . $m->group(1);
print 'ask: ' . $m->group(2);
});