I have a plain text file which have the list of countries as follows.
United Kingdom
United States of America
Abkhazia
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Ashmore and Cartier Islands
Australia
Austria
Azerbaijan
Bahamas
Bahrain
I want to insert all the values in database for which i need to convert this to an array. i am using the following code for reading the file.
$fileContent = file_get_contents('countries.txt');
$fileContent = nl2br($fileContent);
Now i want to add ( , ) comma in the end of each line break. so that i can use explode() and convert it into an array. how do i do it?
thank you.
Not sure why you are doing nl2br
Just try
$fileContent = file_get_contents('countries.txt');
$array = explode("\n", $fileContent);
Use this function instead: file
Assuming the list you posted is actually in the following format after your nl2br() call
United Kingdom<br />
United States of America<br />
Abkhazia<br />
...
You can do
<?PHP
explode("<br />", $yourString);
// or explode("\n", $yourString); if you remove the nl2br() call
?>
Related
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.
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 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 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.
if you search alexa with any URL's you will get a detailed traffic information of the same.
what I am looking into is I would like to parse Visitors by Country info from alexa.
example for google.com
url is - http://www.alexa.com/siteinfo/google.com.
on the Audience tab you can see:
Visitors by Country for Google.com
United States 35.0%
India 8.8%
China 4.1%
Germany 3.4%
United Kingdom 3.2%
Brazil 3.2%
Iran 2.8%
Japan 2.1%
Russia 2.0%
Italy 1.9%
Brazil 3.2%
Iran 2.8%
Japan 2.1%
Russia 2.0%
Italy 1.9%
Indonesia 1.7% //etc.
How can I get only these info from alexa.com?? I have tried with preg_match function but it is very difficult in this case....
If you don't want to use DOM and getElementById which is the most elegant solution in this case, you can try regexp:
$data = file_get_contents('http://www.alexa.com/siteinfo/google.com');
preg_match_all(
'/<a href="\/topsites\/countries\/(.*)">(.*)<\/a>/mU',
$data,
$result,
PREG_SET_ORDER
);
The DOM solution looks like:
$doc = new DomDocument;
$doc->loadHTMLFile('http://www.alexa.com/siteinfo/google.com');
$data = $doc->getElementById('visitors-by-country');
$my_data = $data->getElementsByTagName('div');
$countries = array();
foreach ($my_data as $node)
{
foreach($node->getElementsByTagName('a') as $href)
{
preg_match('/([0-9\.\%]+)/',$node->nodeValue, $match);
$countries[trim($href->nodeValue)] = $match[0];
}
}
var_dump($countries);