Splitting a string by comma while ignoring other commas (not quoted) - php

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

Related

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

php regular expression parse data

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");
}

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
)

PHP line parsed into separate objects

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)

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