Simple question, comma delimited id's to array in php 5.2 - php

I've got a comma delimited string of id's coming in and I need some quick way to split them into an array.
I know that I could hardcode it, but that's just gross and pointless.
I know nothing about regex at all and I can't find a SIMPLE example anywhere on the internet, only huge tutorials trying to teach me how to master regular expressions in 2 hours or something.
fgetcsv is only applicable for a file and str_getcsv is only available in PHP 5.3 and greater.
So, am I going to have to write this by hand or is there something out there that will do it for me?
I would prefer a simple regex solution with a little explanation as to why it does what it does.

$string = "1,3,5,9,11";
$array = explode(',', $string);
See explode()
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .

Any problem with normal split function?
$array = split(',', 'One,Two,Three');
will give you
Array
(
[0] => One
[1] => Two
[2] => Three
)

If you want to just split on commas:
$values = explode(",", $string);
If you also want to get rid of whitespace around the commas (eg: your string is 1, 3, 5)
$values = preg_split('/\s*,\s*/', $string)
If you want to be able to have commas in your string when surrounded by quotes, (eg: first, "se,cond", third)
$regex = <<<ENDOFREGEX
/ " ( (?:[^"\\\\]++|\\\\.)*+ ) \"
| ' ( (?:[^'\\\\]++|\\\\.)*+ ) \'
| ,+
/x
ENDOFREGEX;
$values = preg_split($regex, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

A simple regular expression should do the trick.
$a_ids = preg_split('%,%', $ids);

Related

explode string at "newline,space,newline,space" in PHP

This is the string I'm trying to explode. This string is part of a paragraph which i need to split at every "newline,space,newline,space" :
s
1
A result from textmagic.com show it contains a \n then a space then a \n and then a space.
This is what I tried:
$values = explode("\n\s\n\s",$string); // 1
$values = explode("\n \n ",$string); // 2
$values = explode("\n\r\n\r",$string); // 3
Desired output:
Array (
[0] => s
[1] => 1
)
but none of them worked. What's wrong here?
How do I do it?
Just use explode() with PHP_EOL." ".PHP_EOL." ", which is of the format "newline, space, newline, space". Using PHP_EOL, you get the correct newline-format for your system.
$split = explode(PHP_EOL." ".PHP_EOL." ", $string);
print_r($split);
Live demo at https://3v4l.org/WpYrJ
Using preg_split() to explode() by multiple delimiters in PHP
Just a quick note here. To explode() a string using multiple delimiters in PHP you will have to make use of the regular expressions. Use pipe character to separate your delimiters.
$string = "\n\ranystring"
$chunks = preg_split('/(de1|del2|del3)/',$string,-1, PREG_SPLIT_NO_EMPTY);
// Print_r to check response output.
echo '<pre>';
print_r($chunks);
echo '</pre>';
PREG_SPLIT_NO_EMPTY – To return only non-empty pieces.

How to split string to array while retaining its punctuation mark in PHP [duplicate]

For example, I have an article should be splitted according to sentence boundary such as ".", "?", "!" and ":".
But as well all know, whether preg_split or explode function, they both remove the delimiter.
Any help would be really appreciated!
EDIT:
I can only come up with the code below, it works great though.
$content=preg_replace('/([\.\?\!\:])/',"\\1[D]",$content);
Thank you!!! Everyone. It is only five minutes for getting 3 answers! And I must apologize for not being able to see the PHP manual carefully before asking question. Sorry.
I feel this is worth adding. You can keep the delimiter in the "after" string by using regex lookahead to split:
$input = "The address is http://stackoverflow.com/";
$parts = preg_split('#(?=http://)#', $input);
// $parts[1] is "http://stackoverflow.com/"
And if the delimiter is of fixed length, you can keep the delimiter in the "before" part by using lookbehind:
$input = "The address is http://stackoverflow.com/";
$parts = preg_split('#(?<=http://)#', $input);
// $parts[0] is "The address is http://"
This solution is simpler and cleaner in most cases.
You can set the flag PREG_SPLIT_DELIM_CAPTURE when using preg_split and capture the delimiters too. Then you can take each pair of 2‍n and 2‍n+1 and put them back together:
$parts = preg_split('/([.?!:])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = [];
for ($i = 0, $n = count($parts) - 1; $i <= $n; $i += 2) {
$sentences[] = $parts[$i] . ($parts[$i+1] ?? '');
}
Note to pack the splitting delimiter into a group, otherwise they won’t be captured.
preg_split with PREG_SPLIT_DELIM_CAPTURE flag
For example
$parts = preg_split("/([\.\?\!\:])/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Try T-Regx
<?php
$parts = pattern('([.?!:])')->split($string);
Parsing English sentences has a lot of nuance and fringe cases. This makes crafting a perfect parser very difficult to do. It is important to have sufficient test cases using your real project data to make sure that you are covering all scenarios.
There is no need to use lookarounds or capture groups for this task. You simply match the punctuation symbol(s), then forget them with \K, then match one or more whitespace characters that occurs between sentences. Using the PREG_SPLIT_NO_EMPTY flag prevents creating empty elements if your string starts with or ends with characters that satisfy the pattern.
Code: (Demo)
$str = 'Heading: This is a string. Very exciting! What do you think? ...one more thing, this is cool.';
var_export(
preg_split('~[.?!:]+\K\s+~', $str, 0, PREG_SPLIT_NO_EMPTY)
);
Output:
array (
0 => 'Heading:',
1 => 'This is a string.',
2 => 'Very exciting!',
3 => 'What do you think?',
4 => '...one more thing, this is cool.',
)

Extract strings only from a line in php

I am using explode to extract only strings from a whole line. However using this:
$array = explode(" ", $line);
It splits the line by only one space, not by words. For example if $line is
$line="word1 word2 word3"
then I also have spaces among the entries in the array (it contains: "word1", "word2" and "word3", but also one or two " ").
Does anyone know how to obtain only the three entries "word1", "word2" and "word3" in the array ?
Use preg_split , to split on one or more whitespace characters:
$array = preg_split('/\s+/', $line);
Unlike explode (which splits on a string), preg_split splits on a regular expression, so it is more flexible. If you don't need to use a regular expression for your delimiter, you should instead use explode.
Use str_word_count() with a format code or 1 or 2, and a char list indicating that digits should be considered part of the word, because this will also handle splitting against punctuation marks
$array = str_word_count($line, 1, '0123456789');
Personally I would use Tom Fenech's answer but for your existing code:
$array = array_filter(explode(" ", $line));
You can remove empty array values with array filter:
$array = array_filter(explode(" ", $line));

Regular expression needed for PHP preg_split

I need help with a regular expression in PHP.
I have one string containing a lot of data and the format could be like this.
key=value,e4354ahj\,=awet3,asdfa\=asdfa=23f23
So I have 2 delimiters , and = where , is the set of key and value. The thing is that key and value can contain the same symbols , and = but they will always be escaped. So I cant use explode. I need to use preg_split but I am no good at regular expressions.
Could someone give me a hand with this one?
You need to use negative lookbehind:
// 4 backslashes because they are in a PHP string, so PHP translates them to \\
// and then the regex engine translates the \\ to a literal \
$keyValuePairs = preg_split('/(?<!\\\\),/', $input);
This will split on every , that is not escaped, so you get key-value pairs. You can do the same for each pair to separate the key and value:
list($key, $value) = preg_split('/(?<!\\\\)=/', $pair);
See it in action.
#Jon's answer is awesome. I though of providing a solution by matching the string:
preg_match_all('#(.*?)(?<!\\\\)=(.*?)(?:(?<!\\\\),|$)#', $string, $m);
// You'll find the keys in $m[1] and the values in $m[2]
$array = array_combine($m[1], $m[2]);
print_r($array);
Output:
Array
(
[key] => value
[e4354ahj\,] => awet3
[asdfa\=asdfa] => 23f23
)
Explanation:
(.*?)(?<!\\\\)= : match anything and group it until = not preceded by \
(.*?)(?:(?<!\\\\),|$) : match anything and group it until , not preceded by \ or end of line.

Split text using multiple delimiters into an array of trimmed values

I've got a group of strings which I need to chunk into an array.
The string needs to be split on either /, ,, with, or &.
Unfortunately it is possible for a string to contain two of the strings which needs to be split on, so I can't use split() or explode().
For example, a string could say first past/ going beyond & then turn, so I am trying to get an array that would return:
array('first past', 'going beyond', 'then turn')
The code I am currently using is
$splittersArray=array('/', ',', ' with ','&');
foreach($splittersArray as $splitter){
if(strpos($string, $splitter)){
$splitString = split($splitter, $string);
foreach($splitString as $split){
I can't seem to find a function in PHP that allows me to do this.
Do I need to be passing the string back into the top of the funnel, and continue to go through the foreach() after the string has been split again and again?
This doesn't seem very efficient.
Use a regular expression and preg_split.
In the case you mention, you would get the split array with:
$splitString = preg_split('/(\/|\,| with |\&/)/', $string);
To concisely write the pattern use a character class for the single-character delimiters and add the with delimiter as a value after the pipe (the "or" character in regex). Allow zero or more spaces on either side of the group of delimiters so that the values in the output don't need to be trimmed.
I am using the PREG_SPLIT_NO_EMPTY function flag in case a delimiter occurs at the start or end of the string and you don't want to have any empty elements generated.
Code: (Demo)
$string = 'first past/ going beyond & then turn with everyone';
var_export(
preg_split('~ ?([/,&]|with) ?~', $string, 0, PREG_SPLIT_NO_EMPTY)
);
Output:
array (
0 => 'first past',
1 => 'going beyond',
2 => 'then turn',
3 => 'everyone',
)

Categories