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.
Related
I am working with an API and getting results via an API. I am having trouble with the delimitation to split the array. Below is the sample example data I am receiving from the API:
name: jo mamma, location: Atlanta, Georgia, description: He is a good
boy, and he is pretty funny, skills: not much at all!
I would like to be able to split like so:
name: jo mamma
location: Atlanta, Georgia
description: He is a good boy, and he is pretty funny
skills: not much at all!
I have tried using the explode function and the regex preg_split.
$exploded = explode(",", $data);
$regex = preg_split("/,\s/", $data);
But not getting the intended results because its splitting also after boy, and after Georgia. Results below:
name: jo mamma
location: Atlanta
Georgia
description: He is a good boy
and he is pretty funny
skills: not much at all!
Any help would be greatly appreciated. Thanks.
Just do this simple split using Zero-Width Positive Lookahead . (It will split by only , after which there is text like name:).
$regex = preg_split("/,\s*(?=\w+\:)/", $data);
/*
Array
(
[0] => "name: jo mamma"
[1] => "location: Atlanta, Georgia"
[2] => "description: He is a good boy, and he is pretty funny"
[3] => "skills: not much at all!"
)
*/
Learn more on lookahead and lookbehind from here : http://www.regular-expressions.info/lookaround.html
Use this regex:
name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)
$text = 'name: jo mamma, location: Atlanta, Georgia, description: He is a good boy, and he is pretty funny, skills: not much at all!';
preg_match_all('/name:\s(.*),\slocation:\s(.*),\sdescription:\s(.*),\sskills:\s(.*)/', $text, $text_matches);
for ($index = 1; $index < count($text_matches); $index++) {
echo $text_matches[$index][0].'<br />';
}
Output:
jo mamma
Atlanta, Georgia
He is a good boy, and he is pretty funny
not much at all!
Regex101
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 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
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)
So I have the following PHP string:
$output = {"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians' official Twitter feed reports.","spin":"He'll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}
What I need is: "Accardo was called up from Columbus on Monday, the Indians' official Twitter feed reports." and "He'll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season." as substrings. But I can't seem to figure out the best and most elegant way to do that. I tried to JSON_decode the string but I get nothing returned. Any ideas? (I am using PHP)
That's not a string. Try like this:
$output = '{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians\' official Twitter feed reports.","spin":"He\'ll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}';
$object = json_decode($output);
$array = json_decode($output, true);
$string = json_encode($array);
you have few unescaped string, that is causing the error. a simple formatting could have saved you the time.
$output = '{
"playerId":1178,
"percentChange":0.1,
"averageDraftPosition":260,
"percentOwned":0.1,
"mostRecentNews": {
"news":"Accardo was called up from Columbus on Monday, the Indians official Twitter feed reports",
"spin":"Hell replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.",
"date":"Mon May 14"
},
"fullName":"Jeremy Accardo"
}';
$json = json_decode($output);
Did you try this?
$output = '{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians\' official Twitter feed reports.","spin":"He\'ll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}';
$array = json_decode($output, true);
echo $array['mostRecentNews']['news'];
echo $array['mostRecentNews']['spin'];
json_encode with with only UTF8. are you using allthings with utf8? and you hava synstax error. if you define json variable manually it could be like this;
<?php
$output=<<<JSONSTR
{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians' official Twitter feed reports.","spin":"He'll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}
JSONSTR;
$variable = json_decode($output);
var_dump($variable);
?>