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

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
)

Related

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

Explode a POST variable after a pattern REGEX

I'm terrible at regex, hard to understand for me so I need some help. I have a variable which looks something like this:
["data:image/png;base64,Ivksfk...=", "data:image/png;base64,JksdkJkf...=", "data:image/png;base64,okKJjfeiw...="]
Those are 3 values which I want to split into an array. The way I see it, I want to split it at the comma which comes after a quote ", ". Can someone please help me with the regex for preg_split?
You could try the below code to split the input string according to ", "
<?php
$yourstring = '["data:image/png;base64,Ivksfk...=", "data:image/png;base64,JksdkJkf...=", "data:image/png;base64,okKJjfeiw...="]';
$regex = '~", "~';
$splits = preg_split($regex, $yourstring);
print_r($splits);
?>
Output:
Array
(
[0] => ["data:image/png;base64,Ivksfk...=
[1] => data:image/png;base64,JksdkJkf...=
[2] => data:image/png;base64,okKJjfeiw...="]
)
If you don't want "[,]" in the output then you could try the below code.
<?php
$data = '["data:image/png;base64,Ivksfk...=", "data:image/png;base64,JksdkJkf...=", "data:image/png;base64,okKJjfeiw...="]';
$regex = '~(?<=\["|", ")[^"]*~';
preg_match_all($regex, $data, $matches);
print_r($matches);
?>
Output:
Array
(
[0] => Array
(
[0] => data:image/png;base64,Ivksfk...=
[1] => data:image/png;base64,JksdkJkf...=
[2] => data:image/png;base64,okKJjfeiw...=
)
)
$string = '["data:image/png;base64,Ivksfk...=", "data:image/png;base64,JksdkJkf...=", "data:image/png;base64,okKJjfeiw...="]';
$parts = preg_split('/,\s/', $string);
var_dump($parts);
Program output:
array(3) {
[0]=>
string(34) ""data:image/png;base64,Ivksfk...=""
[1]=>
string(36) ""data:image/png;base64,JksdkJkf...=""
[2]=>
string(37) ""data:image/png;base64,okKJjfeiw...=""
}
So long as the double-quote symbol cannot occur within the double-quotes that contain the content, this pattern should validate and capture the three values:
^\["([^"]+)"\], \["([^"]+)"\], \["([^"]+)"\]$
If double-quotes can appear within the content, or the number of values is variable, then this pattern will not work.

How to use the explode function in PHP using 2 delimeters instead of 1?

Suppose I have the following:
$string = "(a) (b) (c)";
How would I explode it to get the contents inside the parenthesis. If the string's contents were separated by just one symbol instead of 2 I would have used:
$string = "a-b-c";
explode("-", $string);
But how to do this when 2 delimiters are used to encapsulate the items to be exploded?
You have to use preg_split or preg_match instead.
Example:
$string = "(a) (b) (c)";
print_r(preg_split('/\\) \\(|\\(|\\)/', $string, -1, PREG_SPLIT_NO_EMPTY));
Array
(
[0] => a
[1] => b
[2] => c
)
Notice the order is important.
If there is no nesting parenthesis, you can use regular expression.
$string = "(a) (b) (c)";
$res = 0;
preg_match_all("/\\(([^)]*)\\)/", $string, $res);
var_dump($res[1]);
Result:
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
See http://www.ideone.com/70ZlQ
If you know for a fact that the strings will always be of the form (a) (b) (c), with precisely one space between each pair of parentheses and with no characters at the beginning or end, you can avoid having to use regexp functions:
$myarray = explode(') (', substr($mystring, 1, -1));
Try the below code:
<?php
$s="Welcome to (London) hello ";
$data = explode('(' , $s );
$d=explode(')',$data[1]);
print_r($data);
print_r($d);
?>
Output:
Array ( [0] => Welcome to [1] => London) hello )
Array ( [0] => London [1] => hello )
Perhaps use preg_split with an alternation pattern:
http://www.php.net/manual/en/function.preg-split.php
If your delimiters are consistent like that, then you can do this
$string = "(a) (b) (c)";
$arr = explode(") (", $string);
// Then simply trim remaining parentheses off.
$arr[0] = trim($arr[0], "()");
end($arr) = trim($arr[0], "()");
You can try preg_split() function.

PHP: Split string into array, like explode with no delimiter

I have a string such as:
"0123456789"
And I need to split each character into an array.
I, for the hell of it, tried:
explode('', '123545789');
But it gave me the obvious: Warning: No delimiter defined in explode) ..
How would I come across this? I can't see any method off hand, especially just a function.
$array = str_split("0123456789bcdfghjkmnpqrstvwxyz");
str_split takes an optional 2nd param, the chunk length (default 1), so you can do things like:
$array = str_split("aabbccdd", 2);
// $array[0] = aa
// $array[1] = bb
// $array[2] = cc etc ...
You can also get at parts of your string by treating it as an array:
$string = "hello";
echo $string[1];
// outputs "e"
You can access characters in a string just like an array:
$s = 'abcd';
echo $s[0];
prints 'a'
Try this:
$str = '123456789';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
str_split can do the trick. Note that strings in PHP can be accessed just like a character array. In most cases, you won't need to split your string into a "new" array.
Here is an example that works with multibyte (UTF-8) strings.
$str = 'äbcd';
// PHP 5.4.8 allows null as the third argument of mb_strpos() function
do {
$arr[] = mb_substr( $str, 0, 1, 'utf-8' );
} while ( $str = mb_substr( $str, 1, mb_strlen( $str ), 'utf-8' ) );
It can be also done with preg_split() (preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )), but unlike the above example, that runs almost as fast regardless of the size of the string, preg_split() is fast with small strings, but a lot slower with large ones.
Try this:
$str = '546788';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
Try this:
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
The above example will output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
If you want to split the string, it's best to use:
$array = str_split($string);
When you have a delimiter, which separates the string, you can try,
explode('', $string);
Where you can pass the delimiter in the first variable inside the explode such as:
explode(',', $string);
$array = str_split("$string");
will actually work pretty fine, but if you want to preserve the special characters in that string, and you want to do some manipulation with them, then I would use
do {
$array[] = mb_substr($string, 0, 1, 'utf-8');
} while ($string = mb_substr($string, 1, mb_strlen($string), 'utf-8'));
because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters.

Categories