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].
Related
I got this string:
if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)
The String can contain indefinite occurences of conditions.
and I want an array that contains:
array(3) {
[0]=>
string(...) "conditionA==valueA"
[1]=>
string(...) "conditionB==valueB"
[2]=>
string(...) "conditionC==valueC"
}
I am currently using this pattern:
preg_match("/^if\((.+)-(.+)\)/U", $current_step_data_exploded[0], $if_statements);
Also, I need the "ANDs" and "ORs" so I can further check the statements.
My RegEex doesn't deliver. Can somebody help me?
$string = "if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)";
$match = preg_match('/^if\((.+)\)$/', $string, $if);
if ($match) {
$conditions = preg_split('/\-(AND|OR)\-/', $if[1], -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($conditions);
} else {
echo "no matches.";
}
will output:
Array
(
[0] => conditionA==valueA
[1] => AND
[2] => conditionB==valueB
[3] => OR
[4] => conditionC==valueC
)
You could make use of the \G anchor and a capture group:
(?:\bif\((?=[^()]*\))|\G(?!^))(.*?==.*?)(?:-(?:AND|OR)-|\)$)
Explanation
(?: Non capture group
\bif\((?=[^()]*\) Match if( and assert a closing )
| Or
\G(?!^) Assert the current position at the end of the previous match, not at the start
) Close the non capture group
(.*?==.*?)
(?:-(?:AND|OR)-|\)$) Match one of -AND- -OR-or)` and the end of the string
Regex demo | PHP demo
Example
$re = '/(?:\bif\((?=[^()]*\))|\G(?!^))(.*?==.*?)(?:-(?:AND|OR)-|\)$)/';
$str = 'if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)';
preg_match_all($re, $str, $matches);
print_r($matches[1]);
Output
Array
(
[0] => conditionA==valueA
[1] => conditionB==valueB
[2] => conditionC==valueC
)
This is my text:
pagination},queryId:"472f257a40c653c64c666ce877d59d2b", val:"598f257a40c653c64c666ce877d59d2b"
I need to find 472f257a40c653c64c666ce877d59d2b and 598f257a40c653c64c666ce877d59d2b.
These are all between ". I need ONLY strings between " ", and which don't exceds 32.
Here is my code:
preg_match_all('/"^(.*?){32}$"/mis', $get, $results);
You could use :"\K[a-f\d]{32}(?=")
Explanation
Match :"
Reset the starting point of the reported match \K
Match characters from a to f and from 0 to 9 [a-f\d]{32}
A positive lookahead that asserts what follows is a " (?=")
For example:
$re = '/:"\K[a-f\d]{32}(?=")/';
$str = 'pagination},queryId:"472f257a40c653c64c666ce877d59d2b", val:"598f257a40c653c64c666ce877d59d2b"';
preg_match_all($re, $str, $matches);
var_dump($matches[0]);
That would result in:
array(2) {
[0]=>
string(32) "472f257a40c653c64c666ce877d59d2b"
[1]=>
string(32) "598f257a40c653c64c666ce877d59d2b"
}
Output php example
Regex: "([a-z0-9]{32})" or (?<=")[a-z0-9]{32}(?=")
$text = "pagination},queryId:\"472f257a40c653c64c666ce877d59d2b\", val:\"598f257a40c653c64c666ce877d59d2b\"";
preg_match_all("/\"([a-z0-9]{32})\"/", $text, $match);
print_r($match);
Output:
Array
(
[0] => Array
(
[0] => "472f257a40c653c64c666ce877d59d2b"
[1] => "598f257a40c653c64c666ce877d59d2b"
)
[1] => Array
(
[0] => 472f257a40c653c64c666ce877d59d2b
[1] => 598f257a40c653c64c666ce877d59d2b
)
)
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.
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:)(.+))
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.