Exploding a string at 2 newlines as oppose to just 1 - php

I'm trying to explode a string that has more than 1 newline. More specifically, 2 newlines, and I'm not sure how to do it. For example:
$text = "
text1
text2
text3
";
$text = explode(PHP_EOL, $text);
There would be some empty indexes in the array after this. I need to explode at 2 newlines instead of one. How do I do that?

If you are sure on how the newlines are formed (they may contain \n and/or \r), you can do it this way:
$Array = explode("\n\n", $text);
You can also trim the string, to remove newlines at the start and end:
$Array = explode("\n\n", trim($text));

This should work for you:
Just use preg_split() with the flag: PREG_SPLIT_NO_EMPTY set and explode the string with the constant PHP_EOL, e.g.
$arr = preg_split("/". PHP_EOL . "/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
output:
Array ( [0] => text1 [1] => text2 [2] => text3 )

Related

How to cast string into array with only characters in double quotes

I need to cast $string = ("one","two","three,subthree","four") into PHP array like.
$data[0] => "one",
$data[1] => "two",
$data[2] => "three,subthree",
$data[3] => "four"
The issue is that the delimiter in 3rd variable contains comma so explode function is making the string into 5 variables instead of 4.
You can convert the string to JSON string and then decode like this
$string = '("one","two","three,subthree","four")';
$string = str_replace(['(', ')'], ['[', ']'], $string);
$array = json_decode($string, true);
print_r($array);
Working demo.
Edit:
If you have possibilities to have brackets [( or )] in string, you can trim by brackets [( or )] and explode by the delimiter ",". Example:
$string = '("one","two","three,subthree","four")';
$string = trim($string, ' ()');
$array = explode('","', $string);
print_r($array);
Another way is to use preg_match_all() by the patter ~"([^"])+"~
$string = '("one","two","three,subthree","four")';
preg_match_all('~"([^"]+)"~', $string, $array);
print_r($array[0]);
Regex explanation:
" matches a double quote
([^"]+) capturing group
[^"] any characters except double quote
+ one or more occurrence
" matches a double quote
Here's a shorter version to do that:
$string = '("one", "two,three")';
preg_match_all('/"([^"]+)"/', $string, $string);
echo "<pre>";
var_dump($string[1]);
Output:
array(2) {
[0]=>
string(3) "one"
[1]=>
string(9) "two,three"
}
You can use substr to remove the first (" and ") and then use explode:
$string = '("one","two","three,subthree","four")';
$s = substr($string,2,-2);
// now $s is: one","two","three,subthree","four
print_r(explode('","', $s));
Which outputs:
(
[0] => one
[1] => two
[2] => three,subthree
[3] => four
)
Live example: 3v4l
You can use explode with trim
$string = '("one","two","three,subthree","four")';
print_r(explode('","',trim($string,'"()')));
Working example : https://3v4l.org/4ZERb
A simple way which does the processing of quotes for you is to use str_getcsv() (after removing the start and end brackets)...
$string = '("one","two","three,subthree","four")';
$string = substr($string, 1, -1);
print_r(str_getcsv($string));
gives
Array
(
[0] => one
[1] => two
[2] => three,subthree
[3] => four
)
Main thing is that it will also work with...
$string = '("one","two","three,subthree","four",5)';
and output
Array
(
[0] => one
[1] => two
[2] => three,subthree
[3] => four
[4] => 5
)

Match substring in string divided by a dot

I have following strings:
'sample1.sample2'
'sample1.sample2.samaple3'
on so on..
I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).
My code:
$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
works fine only for first case.
You can do it like this
$string = "dużotekstu.tekstpokropce";
$exp = explode(".",$string);
$output = implode(",",$exp);
Output
dużotekstu,tekstpokropce
Try with this code. it may helps you.
You can trim single quotes and then a simple explode on dot:
php> $str = "'sample1.sample2.samaple3'";
php> print_r(explode('.', trim($str, "'")));
Array
(
[0] => sample1
[1] => sample2
[2] => samaple3
)
php> $str = "'sample1.sample2'";
php> print_r(explode('.', trim($str, "'")));
Array
(
[0] => sample1
[1] => sample2
)
why don't you split string using preg_split. You can refer here
Use preg_split() if it has to be a Regex:
$array = preg_split('/\./', $string);

regex code preg_split (:)

For the following code:
$string = "hello: Mister, Winterbottom";
$words = preg_split("/[\s,]+/", $string);
print_r ($words);
I get:
Array ( [0] => hello: [1] => Mister [2] => Winterbottom )
but I want the results to be:
Array ( [0] => hello [1] => Mister [2] => Winterbottom )
so that it will ignore the colon. How can I do it?
If you need to expand your character class with :, just put it inside it and use
/[\s,:]+/
See its demo here. Or, just use /\W+/ to split with 1+ non-word characters.
$words = preg_split("/[\s,:]+/", $string);
print_r ($words);
// Or
print_r(preg_split("/\W+/", $string));
See the PHP demo
$string = "hello: Mister, Winterbottom";
$words = preg_split("/[\s,]+/", $string);
$words[0] = rtrim($words[0],":");
print_r ($words);

Split string on spaces except words in quotes

I have a string like
$string = 'Some of "this string is" in quotes';
I want to get an array of all the words in the string which I can get by doing
$words = explode(' ', $string);
However I don't want to split up the words in quotes so ideally the end array will be
array ('Some', 'of', '"this string is"', 'in', 'quotes');
Does anyone know how I can do this?
You can use:
$string = 'Some of "this string is" in quotes';
$arr = preg_split('/("[^"]*")|\h+/', $string, -1,
PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r ( $arr );
Output:
Array
(
[0] => Some
[1] => of
[2] => "this string is"
[3] => in
[4] => quotes
)
RegEx Breakup
("[^"]*") # match quoted text and group it so that it can be used in output using
# PREG_SPLIT_DELIM_CAPTURE option
| # regex alteration
\h+ # match 1 or more horizontal whitespace
Instead of doing it this way, you can do it in another way aka matching. It will be a lot more easier to match than to split.
So use the regex: /[^\s]+|".*?"/ in conjuction with preg_match_all.
You can get values by match, not by split, with regex:
/"[^"]+"|\w+/g
whis will match:
"[^"]+" - characters between quote signs ",
\w+ - sets of word characters (A-Za-z_0-9),
DEMO
I think you can use a regex like this:
/("[^"]*")|(\S+)/g
And you can use substitution $2
[Regex Demo]

Returning whole string with preg_split

I'm trying to split a string by one or more spaces, but the below isn't working..instead it is returning the whole string as a singular array.
$str = 'I am a test';
$parts = preg_split('/\s+/', $str, PREG_SPLIT_NO_EMPTY);
print_r($parts);
Here is what it returns:
Array
(
[0] => I am a test
)
flags is the 4th parameter to preg_split, not the 3rd.
Remove PREG_SPLIT_NO_EMPTY flag: $parts = preg_split('/\s+/', $str);

Categories