Explode the string to array in php - php

I have a string
string(22) ""words,one","words2""
and need to explode to an array having structure
array( [0] => words,one ,[1] => words2)

To continue on the explode option you mentioned trying, you could try the following:
$str = '"words,one","words2"';
$arr = explode('","', trim($str, '"'));
print_r($arr);
Notice the trim to remove the beginning and ending quote marks, while explode uses the inner quote marks as part of the delimiter.
Output
Array
(
[0] => words,one
[1] => words2
)

I assume your "" is a typo for "\" or '".
I use regex to capture what is inside of " with (.*?) where the ? means be lazy.
I escape the " with \" to make it read them literal.
You will have your words in $m[1].
$str = '"words,one","words2"';
Preg_match_all("/\"(.*?)\"/", $str, $m);
Var_dump($m);
https://3v4l.org/G4m4f
In case that is not a typo you can use this:
Preg_match_all("/\"+(.*?)\"+/", $str, $m);
Here I add a + to each of the " which means "there can be more than one"

Using preg_split you can try :
$str = '"words,one","words2"';
$matches = preg_split("/\",\"/", trim($str, '"'));
print_r($matches);
check : https://eval.in/945572

Assuming the the input string can be broken down as follows:
The surrounding double-quotes are always present and consist of one double-quote each.
"words,one","words2" is left after removing the surrounding double-quotes.
We can extract a csv formatted string that fgetcsv can parse.
Trimming the original and wrapping it in a stream allows us to use fgetcsv. See sample code on eval.in
$fullString= '""words,one","words2""';
$innerString = substr($fullString, 1, -1)
$tempFileHandle = fopen("php://memory", 'r+');
fputs($tempFileHandle , $innerString);
rewind($tempFileHandle);
$explodedString = fgetcsv($tempFileHandle, 0, ',', '"');
fclose($tempFileHandle);
This method also supports other similarly formatted strings:
""words,one","words2""
""words,one","words2","words3","words,4""

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.

Use explode in a smarter way

I have the following string:
$string = "This is my string, that I would like to explode. But not\, this last part";
I want to explode(',', $string) the string, but explode() should not explode when there is a \ in front of the comma.
Wanted result:
array(2) {
[0] => This is my string
[1] => that I would like to explode. But not , this last part
}
I would use preg_split():
$result = preg_split('/(?<!\\\),/', $string);
print_r($result);
(?<!\\\\) is a lookbehind. So a , not preceded by a \. Using \\\ is needed to represent a single \ since it's an escape character.

How to make explode() include the exploded character

$text = "This is /n my text /n wow";
$quotes = explode('/n',$text);
This would split the string into "This is" "My text" "wow"
but I want it to leave the string "/n" as it is, instead of cutting it off,
the output should look like this:
"This is /n" "my text /n" "wow"
Explode your string into an array and then append the separator onto each element of the resulting array.
$sep = "/n";
$text = "This is /n my text /n wow";
$quotes = explode($sep,$text);
$quotes = array_map(function($val) use ($sep) {
return $val . $sep;
}, $quotes);
$last_key = count($quotes)-1;
$quotes[$last_key] = rtrim($quotes[$last_key], $sep);
(Might need to trim($val) as well).
If you have only one possible separator then you can simply append it to the tokens that explode returned. However, if you're asking this question, e.g. because you have multiple possible separators and need to know which one separated two tokens, then preg_split might work for you. E.g. for separators ',' and ';':
$matches = preg_match('/(,|;)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
Have you looked into using the preg_split() function. Per the documentation:
preg_split — Split string by a regular expression
Using this function, apply a positive lookbehind that matches spaces followed by a preceding /n string.
$quotes= preg_split("/(?<=\/n) /", $text);
You can test that this is the desired functionality by doing print_r($quotes); after the above statement. This output from the print_r function will looks similar to the following:
Array ( [0] => This is /n [1] => my text /n [2] => wow )
You may need to use trim() on the values to clear off leading and trailing whitespace but overall it seems to do what you're asking.
DEMO:
If you want to test this functionality out, try copying the following code block and pasting it into the CodeSpace window on http://phpfiddle.org.
<?php
$text = "This is /n my text /n wow";
$values = preg_split("/(?<=\/n) /", $text);
print_r($values);
?>
Select the Run - F9 option to see the output. My apologies for the copy and paste demo example. I couldn't figure out how to create a dedicated URL like some of the other fiddle programs.

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

Extract all strings values from code

everyone. I have a problem and I can't resolve it.
Pattern: \'(.*?)\'
Source string: 'abc', 'def', 'gh\'', 'ui'
I need [abc], [def], [gh\'], [ui]
But I get [abc], [def], [gh\], [, ] etc.
Is it possible? Thanks in advance
PHP Code: Using negative lookbehind
$s = "'abc', 'def', 'ghf\\\\', 'jkl\'f'";
echo "$s\n";
if (preg_match_all("~'.*?(?<!(?:(?<!\\\\)\\\\))'~", $s, $arr))
var_dump($arr[0]);
OUTOUT:
array(4) {
[0]=>
string(5) "'abc'"
[1]=>
string(5) "'def'"
[2]=>
string(7) "'ghf\\'"
[3]=>
string(8) "'jkl\'f'"
}
Live Demo: http://ideone.com/y80Gas
Yes, those matches are possible.
But if you mean to ask whether it's possible to get what's inside the quotes, the easiest here would be to split by comma (through a CSV parser preferably) and trim any trailing spaces.
Otherwise, you could try something like:
\'((?:\\\'|[^\'])+)\'
Which will match either \' or a non-quote character, but will fail against stuff like \\'...
A longer, and slower regex you might use for this case is:
\'((?:(?<!\\)(?:\\\\)*\\\'|[^\'])+)\'
In PHP:
preg_match_all('/\'((?:(?<!\\)\\\'|[^\'])+)\'/', $text, $match);
Or if you use double quotes:
preg_match_all("/'((?:(?<!\\\)\\\'|[^'])+)'/", $text, $match);
Not sure why there's an error with (?<!\\) (I really mean one literal backslash) when it should be working fine. It works if the pattern is changed to (?<!\\\\).
ideone demo
EDIT: Found a simpler, better, faster regex:
preg_match_all("/'((?:[^'\\]|\\.)+)'/", $text, $match);
<?php
// string to extract data from
$string = "'abc', 'def', 'gh\'', 'ui'";
// make the string into an array with a comma as the delimiter
$strings = explode(",", $string);
# OPTION 1: keep the '
// or, if you want to keep that escaped single quote
$replacee = ["'", " "];
$strings = str_replace($replacee, "", $strings);
$strings = str_replace("\\", "\'", $strings);
# OPTION 2: remove the ' /// uncomment tripple slash
// replace the single quotes, spaces, and the backslash
/// $replacee = ["'", "\\", " "];
// do the replacement, the $replacee with an empty string
/// $strings = str_replace($replacee, "", $strings);
var_dump($strings);
?>
Instead you should use str_getcsv
str_getcsv("'abc', 'def', 'gh\'', 'ui'", ",", "'");

Categories