I want the results to be:
Cats, Felines & Cougars
Dogs
Snakes
This is the closest I can get.
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = split(',[^ ]', $string);
print_r($result);
Which results in
Array
(
[0] => Cats, Felines & Cougars
[1] => ogs
[2] => nakes
)
To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.
Use the str. split() method to split a string by comma, e.g. my_list = my_str. split(',') .
You can use a negative lookahead to achieve this:
,(?!\s)
In simple English, the above regex says match all commas only if it is not followed by a space (\s
).
In PHP, you can use it with preg_split()
, like so:
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?!\s)/', $string);
print_r($result);
Output:
Array
(
[0] => Cats, Felines & Cougars
[1] => Dogs
[2] => Snakes
)
the split() function has been deprecated so I'm using preg_split instead.
Here's what you want:
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?! )/', $string);
print_r($result);
This uses ?! to signify that we want split on a comma only when not followed by the grouped sequence.
I linked the Perl documentation on the operator since preg_split uses Perl regular expressions:
http://perldoc.perl.org/perlre.html#Look-Around-Assertions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With