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.
Related
String:
"hello, how are you? you are fine. i am good too."
I want to break this string on the basis of , ? . these characters in php through reg-ex or you can provide me simple reg-ex.
Desired result in an array:
[0]hello
[1]how are you
[2]you are fine
[3]i am good too
Please provide regex for this. again the question is that provide the regex through which i can break the string. Matching characters should be . , ?
You can use preg_split with this regex:
/[^A-Za-z\s]\s*/
It looks for a character which is not a letter or whitespace, followed optionally by one or more spaces. This allows for the situation where there is no space after the punctuation mark. Note we use the PREG_SPLIT_NO_EMPTY flag to preg_split so that if the string ends in a punctuation mark we don't get empty strings in the output.
$string = "hello, how are you?you are fine. i am good too.";
$output = preg_split('/[^A-Za-z\s]\s*/', $string, -1, PREG_SPLIT_NO_EMPTY);
print_r($output);
Output:
Array (
[0] => hello
[1] => how are you
[2] => you are fine
[3] => i am good too
)
Demo on 3v4l.org
You can just use the preg_split method with a regex that matches any non-word character followed by a space and a non-word character at the end of the text.
The if is used to pop the ending empty string present in the array if your input text does contain a punctuation character at the very end of it.
$input = "hello, how are you? you are fine. i am good too.";
$output = preg_split( "/\W(?:\s|$)/", $input );
if(strlen(end($output))==0)
{
array_pop($output);
}
foreach ($output as $item) {
echo $item;
echo "\n";
}
output:
hello
how are you
you are fine
i am good too
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""
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));
Please I have the flowing string :
$str = 'blabla-blabla - 12345, blobl-ooo - 54123, hihihi - 98745';
I want to get in an array blabla-blabla - 12345 and blobl-ooo - 54123 and hihihi - 98745
To do that I'm thinking to use REGEXP so I've tried :
preg_match_all("/\b[\p{L}'-]+|[a-z]+\b/u", $str, $all);
but this get only the string part and not the numbers.
Please any advice masters ?
PS : I can't use list and explode because I don't know the number of elements in my string.
For your regex, try:
preg_match_all('/([\w\-]+ \- \d+),?/u', $str, $all);
\w deals for all letters or digits, and the \d for all digits.
Otherwise, even if you do not know the size of your string, you can use explode:
$parts = explode(', ', $str);
foreach($parts as $part) {
// ...
}
I'm not sure why you can't use explode to split on commas. You don't need to know the number of elements to do that. However, a regex like this should work:
"/[\w\-]+ \- \d+/"
You can use preg_split function for it..
str = 'blabla-blabla - 12345, blobl-ooo - 54123, hihihi - 98745';
$result=preg_split('/,/',$str);
echo "<pre>";
print_r($result);
Output
Array
(
[0] => blabla-blabla - 12345
1 => blobl-ooo - 54123
2 => hihihi - 98745
)
DEMO
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);