regex code preg_split (:) - php

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

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
)

How can I split a semicolon delimited string into separate item from string?

I need to split my string input into an semicolon separate as below.
Original String: Loganathan <logu#gmail.com>; Nathan <nathan#gmail.com>; Tester <tester#gmail.com>;
I need split like
Loganathan, logu#gmail.com
Nathan, nathan#gmail.com
Tester, tester#gmail.com
How can I go about accomplishing this?
You can use explode function. explode link
$str = "Loganathan <logu#gmail.com>; Nathan <nathan#gmail.com>; Tester <tester#gmail.com>;";
$str = str_replace(array(" <",">"),array(", ",""),$str);
$converted = explode(";",$str);
print_r($converted);
Which gives you output like
Array(
[0] => Loganathan, logu#gmail.com
[1] => Nathan, nathan#gmail.com
[2] => Tester, tester#gmail.com
)
Use explode
$str = 'Loganathan <logu#gmail.com>; Nathan <nathan#gmail.com>; Tester <tester#gmail.com>;';
//Removing the "<>" symbols
$str = str_replace("<",",",$str);
$str = str_replace(">","",$str);
$result = explode(";", $str);
print_r(array_filter($result)); //Removing empty array values
Result:
Array
(
[0] => Loganathan ,logu#gmail.com
[1] => Nathan ,nathan#gmail.com
[2] => Tester ,tester#gmail.com
)

Can split the single string by explode?

I looked up splitting the string into array in google.I have found that str_split is working.By explode it's doesn't work in below condition.How can I split the string by explode()?
<?php
$string = "EEEE";
print_r(str_split($string));//Array ( [0] => E [1] => E [2] => E [3] => E )
print_r(explode("",$string));//Empty delimiter error
?>
As indicated by your error, explode requires a delimiter to split the string!
You should try,
$str = "EEEE";
$answer = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
alternative way would be preg_split.

Php split a string escaping quotas

I need to manage escaping in a comma split.
This is a string example:
var1,t3st,ax_1,c5\,3,last
I need this split:
var1
t3st
ax_1
c5\,3
last
Please mind this: "c5\,3" is not splitted.
I tried with this:
$expl=preg_split('#[^\\],#', $text);
But i loose the last char of each split.
use this regex
$str = 'var1,t3st,ax_1,c5\,3,last';
$expl=preg_split('#(?<!\\\),#', $str);
print_r($expl); // output Array ( [0] => var1 [1] => t3st [2] => ax_1 [3] => c5\,3 [4] => last )
working example http://codepad.viper-7.com/pWSu3S
Try with a lookbehind:
preg_split('#(?<!\\),#', $text);
Do a 3 phase approach
First replace \, with someting "unique" like \\
Do your split by ","
Replace \\ with \,
That not as nice as regex but it will work ;)
is this ok ?
<?php
$text = "var1,t3st,ax_1,c5\,3,last";
$text = str_replace("\,", "#", $text);
$xpode = explode(",", $text);
$new_text = str_replace("#", "\,", $xpode);
print_r($new_text);
?>
Output
Array ( [0] => var1 [1] => t3st [2] => ax_1 [3] => c5\,3 [4] => last )

How can I convert a sentence to an array of words?

From this string:
$input = "Some terms with spaces between";
how can I produce this array?
$output = ['Some', 'terms', 'with', 'spaces', 'between'];
You could use explode, split or preg_split.
explode uses a fixed string:
$parts = explode(' ', $string);
while split and preg_split use a regular expression:
$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);
An example where the regular expression based splitting is useful:
$string = 'foo bar'; // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));
$parts = explode(" ", $str);
print_r(str_word_count("this is a sentence", 1));
Results in:
Array ( [0] => this [1] => is [2] => a [3] => sentence )
Just thought that it'd be worth mentioning that the regular expression Gumbo posted—although it will more than likely suffice for most—may not catch all cases of white-space. An example: Using the regular expression in the approved answer on the string below:
$sentence = "Hello my name is peter string splitter";
Provided me with the following output through print_r:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Where as, when using the following regular expression:
preg_split('/\s+/', $sentence);
Provided me with the following (desired) output:
Array
(
[0] => Hello
[1] => my
[2] => name
[3] => is
[4] => peter
[5] => string
[6] => splitter
)
Hope it helps anyone stuck at a similar hurdle and is confused as to why.
Just a question, but are you trying to make json out of the data? If so, then you might consider something like this:
return json_encode(explode(' ', $inputString));

Categories