Comma lost, converted to ampersand when encoding address - php

I have an address along the lines of the following:
123 Main Street, Boston Massachusetts, 02137
I need an address to remain intact through a URL so I tried the following:
echo urlencode($address);
echo rawurlencode($address);
The problem is that the commas keep being converted in to ampersands! 🙄︎
How do I prevent (the client? PHP? I'm not sure here) it from converting commas in to ampersands?
The HTTP query is address and the following is what happens:
print_r($_GET);
Yields:
Array (
[address] => 123 Main Street
[Boston_Massachusetts] =>
[02137] =>
)

If they're getting converted to ampersands, something is going horribly wrong, as both urlencode and rawurlencode convert commas to %2C.
Encoding the string 123 Main Street, Boston Massachusetts, 02137 with rawurlencode should give you 123%20Main%20Street%2C%20Boston%20Massachusetts%2C%2002137.
From here it's simply a matter of using rawurldecode when reading back from the URL to convert the encoded string back to your original string:
$address = "123 Main Street, Boston Massachusetts, 02137";
echo $address; // 123 Main Street, Boston Massachusetts, 02137
$encoded = rawurlencode($address);
echo $encoded; // 123%20Main%20Street%2C%20Boston%20Massachusetts%2C%2002137
$decoded = rawurldecode($encoded);
echo $decoded; // 123 Main Street, Boston Massachusetts, 02137
This can be seen working here.

Related

How do you uppercase only certain parts of a single string that's in format "Town comma Initials"?

I have a single location field where people can enter whatever they want, but generally they will enter something in the format of "Town, Initials". So for example, these entries...
New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND
would ideally become...
New York, NY
Columbia, SC
Charleston
Washington, DC
Bismarck, ND
Obviously I can use ucfirst() on the string to handle the first character, but these are things I'm not sure how to do (if they can be done at all)...
Capitalizing everything after a comma
Lowercasing everything before the comma (aside from the first character)
Is this easily doable or do I need to use some sort of regex function?
You could simply chop it up and fix it.
<?php
$geo = 'New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND';
$geo = explode(PHP_EOL, $geo);
foreach ($geo as $str) {
// chop
$str = explode(',', $str);
// fix
echo
(!empty($str[0]) ? ucwords(strtolower(trim($str[0]))) : null).
(!empty($str[1]) ? ', '.strtoupper(trim($str[1])) : null).PHP_EOL;
}
https://3v4l.org/ojl2M
Though you should not trust the user to enter the correct format. Instead find a huge list of all states and auto complete them in. Perhaps something like https://gist.github.com/maxrice/2776900 - then validate against it.

How to put a comma before and after a word in PHP?

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

Extracting part of a string up to a specific character in PHP

I have a string containing a name and address lines, with a <br /> tag separating the name and each address line. For instance:
John Smith<br />999 Somewhere Lane<br />City, FL 66600
I want to separate the name from the rest of the address using PHP. Is this something that can be done?
explode or substr with strpos
$str = 'John Smith<br />999 Somewhere Lane<br />City, FL 66600';
echo substr($str,0,strpos($str,'<br />')); //John Smith
In this particular case the simplest would be to use explode:
$str = 'John Smith<br />999 Somewhere Lane<br />City, FL 66600';
$tmp = explode('<br />', $str);
$name = $tmp[0];
You may, of course use regex but this is simpler.
This should give you the data even though it looked like this <br>, <br/> <br />, etc.
$text = "John Smith<br />999 Somewhere Lane<br />City, FL 66600"
$data = preg_split("/\<br(\s+)?(\/)?\>/", $text);
print_r($data);
Array
(
[0] => John Smith
[1] => 999 Somewhere Lane
[2] => City, FL 66600
)

How do I reformat imported 'addresses' using an Array?

I need a strategy (and help) to accomplish the following;
I import addresses into the DB in this format:
[ 111 SW 22ND RD, 11111 NE 224TH ST ]
What I need is this:
[111 SW 22nd Road, 11111 NE 244th Street]
So my objective here is two folds:
to lowercase the suffix in the street number [22nd / 144th]
to replace the abbreviated street-type with the full word (first letter capitalized), ie. ST -> Street / RD -> Road
I thought the best way to solve this is to;
Lowercase everything first => 1111 sw 22nd st
Then target the 'direction' (sw) back to capitalized, and
Finally use an Array within an Array to identify and replace specific text. Ie.
Way = [way, WAY, wy, WY]
Street = [street, STREET, st, ST]
Road = [road, ROAD, rd, RD]
Is this the best approach?
If so, how do I approach (#2) targeting and capitalizing the 'direction' (SW, NE, etc), and (#3) what is the array that can identify and replace the abbreviated street-type?
This took care of it all. Worked great!
<?php
$data= $row['ADDRESS'];
$find= array(
'Way'=> array('WY','WAY','Wy'),
'Court'=> array('CT') ,
'Street'=> array(' ST'),
'th'=> array('TH'),
'rd'=> array('RD'),
'nd'=> array('ND'),
'1st'=> array('1ST')
);
foreach($find as $key => $value){
foreach($value as $r){
$data= str_replace($r,$key,$data);
}
}
echo $data;
?>
Noy Hadar

Parsing a string after a certain string

I have a string ($source) which is containing the following data:
{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert's hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw##._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}
I'm extracting the title, the genre, the plot and so on by using this:
foreach(str_getcsv($source) as $item) {
list($k, $v) = explode(':', $item);
$$k = str_replace('"', '', $v);
}
So far, this works very well, I'm able to use $Title, $Genre and so on. The only thing that doesn't work is the URL to the poster since I'm exploding the ':' and the URL - of course - contains ':' (after the 'http').
How can I put the poster URL into a variable?
That looks like JSON data, why not simply:
$txt = '{"Title etc.....}';
$data = json_decode($txt);
$title = $data['Title'];
$genre = $data['Genre'];
etc...
variable variables are highly ugly, and you risk compromising your code by overwriting some other variable with the contents of the JSON data.
if you REALLY insist on poluting your namespace with auto-vivified variables, you can always use extract() to pull apart the array
Use json_decode
$str = '{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert\'s hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw##._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}';
$decode_string = json_decode($str);
print_r($decode_string);
echo $decode_string->Title;
Here is the running code Click Here
Its a json,
You should use json_decode
$str = '{"Title":"War Horse","Year":"2011","Rated":"PG-13","Released":"25 Dec 2011","Runtime":"2 h 26 min","Genre":"Drama, War","Director":"Steven Spielberg","Writer":"Lee Hall, Richard Curtis","Actors":"Jeremy Irvine, Emily Watson, David Thewlis, Benedict Cumberbatch","Plot":"Young Albert enlists to serve in World War I after his beloved horse is sold to the cavalry. Albert\'s hopeful journey takes him out of England and across Europe as the war rages on.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5MjgyNDY2NV5BMl5BanBnXkFtZTcwNjExNDc1Nw##._V1_SX640.jpg","imdbRating":"7.2","imdbVotes":"39,540","imdbID":"tt1568911","Response":"True"}';
$arr = json_decode($str,true);
print_r($arr);
echo $arr['Title'];
echo $arr['Year'];
Notice, I have properly escaped the string.

Categories