PHP Complex String Parse, JSON'able? - php

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

Related

Split string by full stop in php exclude "a.m."

I am using the preg_split function in PHP to split a paragraph to be several sentences.
In my case:
$str = 'Applicants can check the final result of Admissions through the online enquiry system. The online enquiry system will be available from 10:00 a.m. on November 16 (Wednesday).';
$arr = preg_split('/\./', $str);
How can I exclude the case when there is an a.m. or p.m.?
You should be able to use (*SKIP)(*FAIL) to block the am/pm matches. You can read more about the approach here, http://www.rexegg.com/regex-best-trick.html.
[ap]\.m\.(*SKIP)(*FAIL)|\.
Regex Demo: https://regex101.com/r/uD9xD7/1
Demo: https://eval.in/548705
PHP Usage:
$str = 'Applicants can check the final result of Admissions through the online enquiry system. The online enquiry system will be available from 10:00 a.m. on November 16 (Wednesday).';
$arr = preg_split('/[ap]\.m\.(*SKIP)(*FAIL)|\./', $str);
print_r($arr);
Output:
Array
(
[0] => Applicants can check the final result of Admissions through the online enquiry system
[1] => The online enquiry system will be available from 10:00 a.m. on November 16 (Wednesday)
[2] =>
)
If A.M. should also be allowed use the i modifier.

How to remove set off string in PHP [duplicate]

This question already has answers here:
How to remove a substring from a string using PHP?
(4 answers)
Closed 7 years ago.
I have this string variable in my PHP code:
I am getting this value from DB.
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
How to remove this sentence ('Kindly Note: Before 72Hrs Cancellation full refund') from the string.
I have to remove the text which come after this text('Kindly Note:') from the given string How to do that.
Some time I get different text after this text('Kindly Note: We dont allow 24hrs checkin') So I want to remove text whatever comes after this text('Kindly Note:');
Since I love exploding things...try this logic, will remove anything beyond the "Kindly Note:" part:
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$arr_includes = explode('Kindly Note:', $includes);
$include = $arr_includes[0];
output:
~ All taxes~ Complimentary Buffet Breakfast,~ Complimentary Wi-Fi~ Complimentary Fruit Basket only for Suite RoomFacilities and Services:~ 24Hrs Room Service~ Lounge~ Direct Dialing STD and ISD facilities
use chop()
echo chop($includes,'Before 72Hrs Cancellation full refund');
or
echo chop($includes,'Kindly Note:<br/>Before 72Hrs Cancellation full refund');
Edit 1
use
echo substr($includes, 0, strpos($includes, "Kindly Note:"));
Use str_replace simply.
str_replace('Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $includes);
Simple:
if ($dbText === 'your text') {
$dbText = 'your replacement text';
}
or change the text in the database itself. If you need something else, please elaborate on your requirements. Things like string replacement or regular expression replacement come to mind for more generic problems.
If it comes always end of the string the you can use
substr($string, 0, -3);
use str_replace function
$s = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$new_string = str_replace('<br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $s);
Assume "Kindly Note:" exists in the string and you want to remove anything after the "Kindly Note:"
echo strstr($includes, "Kindly Note:", true);

Querying Content from Wikipedia

I am trying to fetch the first para of the Wikipedia article using the following script. When i query with multiple words it doesn't work.
<?php
$query = urlencode($_GET['query']);
$url = "http://en.wikipedia.org/w/api.php?action=parse&page=$query&format=json&prop=text&section=0";
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "TestScript"); // required by wikipedia.org server; use YOUR user agent with YOUR contact information. (otherwise your IP might get blocked)
$c = curl_exec($ch);
$json = json_decode($c);
$content = $json->{'parse'}->{'text'}->{'*'}; // get the main text content of the query (it's parsed HTML)
// pattern for first match of a paragraph
$pattern = '#<p>(.*)</p>#Us'; // http://www.phpbuilder.com/board/showthread.php?t=10352690
if(preg_match($pattern, $content, $matches))
{
// print $matches[0]; // content of the first paragraph (including wrapping <p> tag)
$cont = strip_tags($matches[1]); // Content of the first paragraph without the HTML tags.
}
$pattern = '/\[([^\[\]]|(?R))*]|\(([^()]|(?R))*\)/';
echo $my = preg_replace($pattern, '', $cont);
?>
Demo 1: Bangalore
Demo 2: Los Angeles
Is there anyway to query for the results from Wikipedia and by default select the first Result.
You need to url encode your query string before passing it to curl.
<?php $query = urlencode($_GET['query']); ?>
EDIT: I tried your code and it worked by replacing whitespaces by the character '+'.
The url encode did not work because it replaced them by '%20'.
Try this
$query = str_replace(' ', '+', $_GET['query']);
Here is the output I get with Los Angeles and New Delhi
iMac-de-Valentin:so valentin$ php so.php
Los Angeles , officially the City of Los Angeles, often known by its initials L.A., is the most populous city in the U.S. state of California and the second-most populous in the United States, after New York City, with a population at the 2010 United States Census of 3,792,621. It has a land area of 469 square miles , and is located in Southern California.
iMac-de-Valentin:so valentin$ php so.php
New Delhi i/ˈnjuː dɛli/ is the capital of India and seat of the executive, legislative, and judiciary branches of the Government of India. It is also the centre of the Government of the National Capital Territory of Delhi. New Delhi is situated within the metropolis of Delhi and is one of the eleven districts of Delhi National Capital Territory.
iMac-de-Valentin:so valentin$

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.

PHP: How to find the beginning and end of a substring in a string?

This is the content of one mysql table field:
Flash LEDs: 0.5W
LED lamps: 5mm
Low Powers: 0.06W, 0.2W
Remarks(1): this is remark1
----------
Accessories: Light Engine
Lifestyle Lights: Ambion, Crane Fun
Office Lights: OL-Deluxe Series
Street Lights: Dolphin
Retrofits: SL-10A, SL-60A
Remarks(2): this is remark2
----------
Infrared Receiver Module: High Data Rate Short Burst
Optical Sensors: Ambient Light Sensor, Proximity Sensor, RGB Color Sensor
Photo Coupler: Transistor
Remarks(3): this is remark3
----------
Display: Dot Matrix
Remarks(4): this is remark4
Now, I want to read the remarks and store them in a variable. Remarks(1), Remarks(2), etc. are fixed. 'this is remark1', etc. come from form input fields, so they are flexible.
Basically what I need is: Read everything between 'Remarks(1):' and '--------' and save it in a variable.
Thanks for your help.
You can use regex:
preg_match_all("~Remarks\(([^)]+)\):([^\n]+)~", $str, $m);
As seen on ideone.
The regex will put X in match group 1, Y in match group 2 (Remarks(X): Y)
This would be a job for regular expressions, which allow you to match on exactly the kinds of rules your requirements express. Here is a tutorial for you.
Use preg function for this or otherwise you can explode and implode function to get correct result. Don't Use Substring it may not provide correction.
Example of Implode and Explode Function for your query string :
$sdr = "Remarks(4): this is remark4";
$sdr1 = explode(":",$sdr);
$frst = $sdr1[0];
$sdr2 = array_shift($sdr1);
$secnd = implode(" ", $sdr1);
echo "First String - ".$frst;
echo "<br>";
echo "Second String - ".$secnd;
echo "<br>";
Your Answer :
First String - Remarks(4)
Second String - this is remark4

Categories