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.
Related
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
)
I have this sample string in a source:
#include_plugin:PluginName param1=value1 param2=value2#
What I want is to find all occurances of #include_plugin:*# from a source with a result of the PluginName and each paramN=valueN.
At this moment I'm fiddling with something like this (and have tried many variants): /#include_plugin:(.*\b){1}(.*\=.*){0,}#/ (using this resource). Unfortunately I can't seem to define a pattern which is giving me the result I want. Any suggestions?
Update with example:
Say I have this string in a .tpl-file. #include_plugin:BestSellers limit=5 fromCategory=123#
I want it to return an array with:
0 => BestSellers,
1 => limit=5 fromCategory=123
Or even better (if possible):
0 => BestSellers,
1 => limit=5,
2 => fromCategory=123
You can do it in 2 steps. First capture the line with a regex, then explode the parameters into an array:
$subject = '#include_plugin:PluginName param1=value1 param2=value2#';
$pattern = '/#include_plugin:([a-z]+)( .*)?#/i';
preg_match($pattern, $subject, $matches);
$pluginName = $matches[1];
$pluginParams = isset($matches[2])?explode(' ', trim($matches[2])):array();
You can use this regex:
/#include_plugin:([a-zA-Z0-9]+)(.*?)#/
The PluginName is in the first capturing group, and the parameters are in the second capturing group. Note that the parameters, if any, has a leading spaces.
It is not possible to write a regex to extract to your even better case, unless the maximum number of parameters in known.
You can do extra processing by first trimming leading and trailing spaces, then split along /\s+/.
I'm not sure of your character-set that your PluginName can contain, or the parameters/values, but in case they are limited you can use the following regex:
/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/
This will capture the plugin name followed by any list of alpha-numeric parameters with their values. The output can be seen with:
<?
$str = '#include_plugin:PluginName param1=value1 param2=value2#
#include_plugin:BestSellers limit=5 fromCategory=123#';
$regex = '/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/';
$matches = array();
preg_match_all($regex, $str, $matches);
print_r($matches);
?>
This will output:
Array
(
[0] => Array
(
[0] => #include_plugin:PluginName param1=value1 param2=value2#
[1] => #include_plugin:BestSellers limit=5 fromCategory=123#
)
[1] => Array
(
[0] => PluginName param1=value1 param2=value2
[1] => BestSellers limit=5 fromCategory=123
)
)
To get the array in the format you need, you can iterate through the results with:
$plugins = array();
foreach ($matches[1] as $match) {
$plugins[] = explode(' ', $match);
}
And now you'll have the following in $plugins:
Array
(
[0] => Array
(
[0] => PluginName
[1] => param1=value1
[2] => param2=value2
)
[1] => Array
(
[0] => BestSellers
[1] => limit=5
[2] => fromCategory=123
)
)
$string = "#include_plugin:PluginName1 param1=value1 param2=value2# #include_plugin:PluginName2#";
preg_match_all('/#include_plugin:([a-zA-Z0-9]+)\s?([^#]+)?/', $string, $matches);
var_dump($matches);
is this what you are looking for?
array(3) {
[0]=>
array(2) {
[0]=>
string(55) "#include_plugin:PluginName1 param1=value1 param2=value2"
[1]=>
string(27) "#include_plugin:PluginName2"
}
[1]=>
array(2) {
[0]=>
string(11) "PluginName1"
[1]=>
string(11) "PluginName2"
}
[2]=>
array(2) {
[0]=>
string(27) "param1=value1 param2=value2"
[1]=>
string(0) ""
}
}
This Regex will give you multiple groups, one for each plugin.
((?<=#include_plugin:)(.+))
Not entirely sure this is possible, but hoping to be pleasantly surprised.
I have a regular expression that looks like this:
$pattern = '#post/date/(\d\d\d\d)-(\d\d)-(\d\d)#';
And, I even have a string that matches it:
$string = 'post/date/2012-01-01';
Of course, I don't know the exact pattern and string beforehand, but they will look something like this.
I need to end up with an array that looks like this:
$groups = array('2012', '01', '01);
The array should contain the parts of the string that matched the three regular expression groups that are within parentheses. Is this possible?
those things between parentheses are subpatterns and you can get the results for each of them when you apply the regex. you can use preg_match_all like this
$string = 'post/date/2012-01-01';
$pattern = '#post/date/(\d\d\d\d)-(\d\d)-(\d\d)#';
preg_match_all($pattern, $string, $matches);
$groups = array($matches[1][0], $matches[2][0],$matches[3][0]);
echo '<pre>';
print_r($groups);
echo '</pre>';
sure, this is an example that just shows the behavior, you will need to check first if the string matched the pattern and if it did, how many times..
you can see that piece of code working here: http://ideone.com/zVu75
Not a regular expression but will do what you want to achieve
<?php
$string = 'post/date/2012-01-01';
$date= basename($string);
$array=explode('-',$date);
print_r($array);
?>
The output array will look like this
Array
(
[0] => 2012
[1] => 01
[2] => 01
)
$str = 'post/date/2012-01-01';
preg_match('#post/date/(\d+)-(\d+)-(\d+)#', $str, $m);
array_shift($m);
$group = $m;
print_r($group);
Output
Array
(
[0] => 2012
[1] => 01
[2] => 01
)
If you're looking for something concise:
$matches = sscanf($string, '%*[^0-9]%d-%d-%d');
makes $matches:
array(3) {
[0]=> int(2012)
[1]=> int(1)
[2]=> int(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.
I have a string of the form "a-b""c-d""e-f"...
Using preg_match, how could I extract them and get an array as:
Array
(
[0] =>a-b
[1] =>c-d
[2] =>e-f
...
[n-times] =>xx-zz
)
Thanks
You can do:
$str = '"a-b""c-d""e-f"';
if(preg_match_all('/"(.*?)"/',$str,$m)) {
var_dump($m[1]);
}
Output:
array(3) {
[0]=>
string(3) "a-b"
[1]=>
string(3) "c-d"
[2]=>
string(3) "e-f"
}
Regexp are not always the fastest solution:
$string = '"a-b""c-d""e-f""g-h""i-j"';
$string = trim($string, '"');
$array = explode('""',$string);
print_r($array);
Array ( [0] => a-b [1] => c-d [2] => e-f [3] => g-h [4] => i-j )
Here's my take on it.
$string = '"a-b""c-d""e-f"';
if ( preg_match_all( '/"(.*?)"/', $string, $matches ) )
{
print_r( $matches[1] );
}
And a breakdown of the pattern
" // match a double quote
( // start a capture group
. // match any character
* // zero or more times
? // but do so in an ungreedy fashion
) // close the captured group
" // match a double quote
The reason you look in $matches[1] and not $matches[0] is because preg_match_all() returns each captured group in indexes 1-9, whereas the entire pattern match is at index 0. Since we only want the content in the capture group (in this case, the first capture group), we look at $matches[1].