Split string into array by regular expression without bracket - php

My string variable contains "[100][200][300][400]" data.
This variable should be split it into array without brackets.
Currently I can split into $matches array with regular expression, but bracket appear in array.
I have used current expression as bellow:
preg _match_all('/\[.*?\]/', $string , $matches)

why not try this:
<?php
$str = " [100][200][300][400] ";
$str = explode("][", trim($str, "[] "));
print_r($str);
exit;

This code maybe can help
$str = "[100][200][300][400]";
$str = explode("][",trim($str,'\[\]'));
Results in:
Array(
[0] => 100
[1] => 200
[2] => 300
[3] => 400
)

Use brackets to choose what part of the match you want to return.
preg_match_all('/\[(.*?)\]/', $string , $matches)

Related

How to extract substrings with delimiters from a string in php

I would like to remove substrings from a string that have delimiters.
Example:
$string = "Hi, I want to buy an [apple] and a [banana].";
How do I get "apple" and "banana" out of this string and in an array? And the other parts of the string "Hi, I want to buy an" and "and a" in another array.
I apologize if this question has already been answered. I searched this site and couldn't find anything that would help me. Every situation was just a little different.
You could use preg_split() thus:
<?php
$pattern = '/[\[\]]/'; // Split on either [ or ]
$string = "Hi, I want to buy an [apple] and a [banana].";
echo print_r(preg_split($pattern, $string), true);
which outputs:
Array
(
[0] => Hi, I want to buy an
[1] => apple
[2] => and a
[3] => banana
[4] => .
)
You can trim the whitespace if you like and/or ignore the final fullstop.
preg_match_all('(?<=\[)([a-z])*(?=\])', $string, $matches);
Should do what you want. $matches will be an array with each match.
I assume you want words as values in the array:
$words = explode(' ', $string);
$result = preg_grep('/\[[^\]]+\]/', $words);
$others = array_diff($words, $result);
Create an array of words using explode() on a space
Use a regex to find [somethings] using preg_grep()
Find the difference of all words and [somethings] using array_diff(), which will be the "other" parts of the string

php regex - get content with square brackets escaped inside square brackets

this is some hard, I have solutions for this with srtpos, but it's ugly, I need help to do it with preg_pos or preg_match . I have a string like below:
$text="Some
[parameter=value\[anoter value|subparam=20] with or
[parameter|value\]anoter value|subparam=21|nothing] or
[parameter=value\[anoter value\]|subparam=22] ";
... I would like to get the following result:
array (
0 => '=value[anoter value|subparam=20',
1 => '|value[anoter value|subparam=21|nothing',
2 => '=value[anoter value]|subparam=22',
)
I mean i know my parameter: [parameter---get this section---] after 'parameter' all text can be to change, and it can contains escaped: bracket - square bracket - parenthesis - ampersand.
thanks !
Use \K to discard the previously matched characters.
\[parameter\K(?:\\[\]\[]|[^\[\]])*
DEMO
$re = "~\\[parameter\\K(?:\\\\[\\]\\[]|[^\\[\\]])*~m";
$str = "Some \n[parameter=value\[anoter value|subparam=20] with or \n[parameter|value\]anoter value|subparam=21|nothing] or \n[parameter=value\[anoter value\]|subparam=22] \";\nfoo bar";
preg_match_all($re, $str, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => =value\[anoter value|subparam=20
[1] => |value\]anoter value|subparam=21|nothing
[2] => =value\[anoter value\]|subparam=22
)
)
Even if you extract the substrings you are interested by, you will need to remove the escaped square brackets in a second time. Let's see the full solution:
$pattern = '~\[\w+\K[^]\\\]*(?:(?:\\\.)+[^]\\\]*)*+(?=])~s';
if (preg_match_all($pattern, $str, $m))
$result = array_map(function ($item) {
return strtr($item, array('\]' => ']', '\[' => '['));
}, $m[0]);

Regular expression with PHP to replace newlines

I am trying to replace all the \n in a json string with a double pipe ||. Here is an example of a string :
{"comment":"test1
test2
test3"}';
Here is the regex I have done :
preg_match('/"comment":"(([^\n\t\r"]*)([\n\t\r]*))+"/', $a, $t);
The result of this preg_match is
Array
(
[0] => "comment":"test1
test2
test3"
[1] =>
[2] =>
[3] =>
)
I can't find what is wrong with my regexp.
Do I need a recursive pattern (?R) ?
Thanks.
Use preg_replace function like below. I assumed that your input have balanced paranthesis.
preg_replace('~(?:"comment"[^\n]*|\G)\K\n([^{}\n]*)~', '||\1', $str)
DEMO
\n+(?=[^{]*})
You can simply use this.Replace with ||.
$re = "/\\n+(?=[^{]*})/i";
$str = "{\"comment\":\"test1\n test2\n test3\"}'";
$subst = "||";
$result = preg_replace($re, $subst, $str);

How to split a string into an array using a given regex expression

I am trying to explode / preg_split a string so that I get an array of all the values that are enclosed in ( ). I've tried the following code but I always get an empty array, I have tried many things but I cant seem to do it right
Could anyone spot what am I missing to get my desired output?
$pattern = "/^\(.*\)$/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
Current output Array ( [0] => [1] => )
Desired output Array ( [0] => "(y3,x3)," [1] => "(r4,t4)" )
With preg_split() your regex should be matching the delimiters within the string to split the string into an array. Your regex is currently matching the values, and for that, you can use preg_match_all(), like so:
$pattern = "/\(.*?\)/";
$string = "(y3,x3),(r4,t4)";
preg_match_all($pattern, $string, $output);
print_r($output[0]);
This outputs:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
)
If you want to use preg_split(), you would want to match the , between ),(, but without consuming the parenthesis, like so:
$pattern = "/(?<=\)),(?=\()/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
This uses a positive lookbehind and positive lookahead to find the , between the two parenthesis groups, and split on them. It also output the same as the above.
You can use a simple regex like \B,\B to split the string and improve the performance by avoiding lookahead or lookbehind regex.
\B is a non-word boundary so it will match only the , between ) and (
Here is a working example:
http://regex101.com/r/cV7bO7/1
$pattern = "/\B,\B/";
$string = "(y3,x3),(r4,t4),(r5,t5)";
$result = preg_split($pattern, $string);
$result will contain:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
[2] => (r5,t5)
)

Explode with regexp

i have a string like {ASK(Value, Value, 'Sentence', Some_Char)} and i need to get of exploded values in (). What i am doing wrong?
preg_match_all('/\{ASK\((.*?),\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
print_r($matches);
Take out the comma from your regular expression, and it matches.
preg_match_all('/\{ASK\((.*?)\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
print_r($matches);
//Explode the matched group
$exploded = explode(',',$matches[1]);
print_r($exploded);
/*
* Note that we used $matches[1] instead of $matches[0],
* since the first element contains the entire matched
* expression, and each subsequent element contains the matching groups.
*/
$s = "{ASK(Value, Value, 'Sentence', Some_Char)}";
$p = '#\{ASK\((.*?)\)\}#';
preg_match_all($p, $s, $matches);
print_r($matches);
Simply split & explode
$Myval = "{ASK(Value, Value, 'Sentence', Some_Char)}";
$splitedVal = split('[()]', $Myval);
$explodedVal = explode(",", $splitedVal[1]);
print_r($explodedVal);
// output
Array ( [0] => Value [1] => Value [2] => 'Sentence' [3] => Some_Char )
An easy way to do this (though not entirely contained within the regex) might be:
preg_match_all('/\{ASK\([^)]*\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
$values = explode($matches[1]);
So long as your Values, Sentences, and Chars do not contain , or ), then this single regex pattern will deliver without the extra explode() call.
Pattern: ~(?:\G, |ASK\()\K[^,)]+~ (Pattern Demo)
Code: (Demo)
$string="{ASK(Value, Value, 'Sentence', Some_Char)}";
print_r(preg_match_all('~(?:\G, |ASK\()\K[^,)]+~',$string,$out)?$out[0]:[]);
Output:
Array
(
[0] => Value
[1] => Value
[2] => 'Sentence'
[3] => Some_Char
)
The "magic" is in the \G. This tells regex to continue matching at the start of the string or just after the previous match. Here is a similar answer that I've posted: https://stackoverflow.com/a/48373347/2943403

Categories