Remove spaces before and after parentheses - php

I'm trying to remove one or more spaces after open parentheses and before close parentheses for both round and square parentheses.
$s = "This is ( a sample ) [ string ] to play with"
expected result:
"This is (a sample) [string] to play with"
I managed to remove the space before:
$s = preg_replace('/\s+(?=[\])])/', '', $s);
result:
"This is ( a sample) [ string] to play with"
but not the spaces after the parentheses!

Try this regex:
(?<=[([]) +| +(?=[)\]])
Click for Demo
Replace the matches with a blank string
Explanation:
(?<=[([]) + - matches 1+ occurrences of a space which are preceded by either a [ or (
| - OR
+(?=[)\]]) - matches 1+ occurrences of a space which are followed either by ) or ]

Related

I need preg_match_all() pattern in getting string inside square bracket tags PHP

I want to parse a string to get the value inside a square bracket tag:
[vc_column_text][/vc_column_text]
I am using preg_match_all() in PHP
$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]`;
I tried this:
preg_match_all("'[vc_column_text(.*?)](.*?)[/vc_column_text]'", $string, $matches);
But this only returns an array of 2-3 characters:
A help will be very much appreciated :)
If you want to match only the sentence, you could use first match [vc_column_text followed by any char except [ or ] and then match the closing ]
Then match 0+ occurrences of a whitespace char and capture 1 or more occurrences of any char except a whitespace in group 1.
\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]
Explanation
\[vc_column_text Match [vc_column_text
[^][]*\] Match [, then 0+ occurrences of any char except [ or ] and match ]
\s* Match 0+ whitespace chars
(.+?) Capture group 1, match any char 1+ times non greedy
\[/vc_column_text] Match [/vc_column_text]
Regex demo | Php demo
Example code
$string = '[vc_row][vc_column][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text css=".vc_custom_1576642149231{margin-bottom: 0px !important;}"]This is the string I want to fetch[/vc_column_text][/vc_column][/vc_row]';
preg_match_all("~\[vc_column_text[^][]*\]\s*(.+?)\[/vc_column_text]~", $string, $matches);
print_r($matches[1]);
Output
Array
(
[0] => This is the string I want to fetch
)

regex expected value in a postion depends on a random value in another position

I need regex to find all shortcode tag pairs that look like this [sc1-g-data]b[/sc1-g-data] but the number next to the sc can vary but they must match.
So something like this won't work \[sc(.*?)\-((.|\n)*?)\[\/sc(.*?)\- as this matches unmatching tag pairs like this which i don't want [sc1-g-data]b[/sc2-g-data]
so the expected number in the second tag depends on a random number in the first tag
You may use a regex like:
\[(sc\d*-[^\]\[]*)\]([\s\S]*?)\[\/\1\]
See the regex demo
\[ - a [ char
(sc\d*-[^\]\[]*) - Capturing group 1: sc, 0+ digits, -, and then 0+ chars other than ] and [
\] - a ] char
([\s\S]*?) - Capturing group 2: any 0+ chars, as few as possible
\[\/ - a [/ string
\1 - the same text stored in Group 1
\] - a ] char
See the regex graph:
PHP demo:
$pattern = '~\[(sc\d*-[^][]*)](.*?)\[/\1]~s';
$string = '[sc1-g-data]a[/sc1-g-data] ';
if (preg_match($pattern, $string, $matches)) {
print_r($matches);
}
Mind the use of a single quoted string literal, if you use a double quoted one you will need to use \\1, not \1 as '\1' != "\1" in PHP.
Output:
Array
(
[0] => [sc1-g-data]a[/sc1-g-data]
[1] => sc1-g-data
[2] => a
)
If your tags are just anything between brackets [blah][/blah] you can use:
\[(.*?)\].*?\[\/\1\]

get all text between bracket but skip nested bracket

Im trying to figure out how to get the text between two bracket tags but dont stop at the first closing )
__('This is a (TEST) all of this i want') i dont want any of this;
my current pattern is __\((.*?)\)
which gives me
__('This is a (TEST)
but i want
__('This is a (TEST) all of this i want')
Thanks
You may use a regex subroutine to match text inside nested parentheses after __:
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
See the regex demo.
Details
__ - a __ substring
(\(((?:[^()]++|(?1))*)\)) - Group 1 (it will be recursed using the (?1) subroutine):
\( - a ( char
((?:[^()]++|(?1))*) - Group 2 capturing 0 or more repetitions of any 1+ chars other than ( and ) or the whole Group 1 pattern is recursed
\) - a ) char.
See the PHP demo:
$s = "__('This is a (TEST) all of this i want') i dont want any of this; __(extract this)";
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
// => Array ( [0] => 'This is a (TEST) all of this i want' [1] => extract this )
You forgot to escape two parenthesis in your regex : __\((.*)\);
Check on regex101.com.
Use the pattern __\((.*)?\).
The \ escapes the parentheses to catch literal parentheses. This then captures all the text inside that set of parentheses.

How to get the text between any number of parenthesis?

Suppose I have a document where I want to capture the strings that have parenthesis before or after.
Example: This [is] a {{test}} sentence. The (((end))).
So basically I want to get the words is, test and end.
Thanks in advance.
According to your condition "strings that have parenthesis before or after" - any word could be proceeded with OR only followed by some type of parentheses:
$text = 'This [is] a {{test}} sentence. The (((end))). Some word))';
preg_match_all('/(?:\[+|\{+|\(+)(\w+)|(\w+)(?:\]+|\}+|\)+)/', $text, $m);
$result = array_filter(array_merge($m[1],$m[2]));
print_r($result);
The output:
Array
(
[0] => is
[1] => test
[2] => end
[7] => word
)
The below code works for me.
<?php
$in = "This [is] a {{test}} sentence. The (((end))).";
preg_match_all('/(?<=\(|\[|{)[^()\[\]{}]+/', $in, $out);
echo $out[0][0]."<br>".$out[0][1]."<br>".$out[0][2];
?>
Your regex could be:
[\[{(]((?(?<=\[)[^\[\]]+|(?(?<={)[^{}]+|[^()]+)))
Explanation: the if-then-else construction is needed to make sure that an opening '{' is matched against a closing '}', etc.
[\[{(] # Read [, { or (
((?(?<=\[) # Lookbehind: IF preceding char is [
[^\[\]]+ # THEN read all chars unequal to [ and ]
| # ELSE
(?(?<={) # IF preceding char is {
[^{}]+ # THEN read all chars unequal to { and }
| # ELSE
[^()]+))) # read all chars unequal to ( and )
See regex101.com
Try this Regex:
(?<=\(|\[|{)[^()\[\]{}]+
>>>Demo<<<
OR this one:
(?<=\(|{|\[)(?!\(|{|\[)[^)\]}]+
>>>Demo<<<
Explantion(for the 1st regex):
(?<=\(|\[|{) - Positive lookbehind - looks for a zero-length match just preceeded by a { or [ or a (
[^()\[\]{}]+ - one or more occurences of any character which is not amoong the following characters: [, (, {, }, ), ]
Explanation(for 2nd Regex):
(?<=\(|\[|{) - Positive lookbehind - looks for a zero-length match just preceeded by a { or [ or a (
(?!\(|{|\[) - Negative lookahead - In the previous step, it found the position which is just preceded by an opening bracket. This piece of regex verifies that it is not followed by another opening bracket. Hence, matching the position just after the innermost opening bracket - (, { or [.
[^)\]}]+ - One or more occurrences of characters which are not among these closing brackets - ], }, )

extract string in double quotation(there are pair double quotations at string)

i have a string
$sting=
' [
type="user"
name="ali"
key="#$WRE"
//problem
address="{
"type":"hellow"
}"
]';
and i extract data with key=value format
for (;;) {
if(!preg_match('~([A-Za-z0-9]+)\=\"([^\"]*)\"~m', $string,$match)){
break;
}
$string=str_replace($match[0], '', $string);
$dataArray[$match[1]]=$match[2];
}
echo "<br><pre>";
print_r($dataArray);
echo "<br></pre>";
but output is
<br><pre>Array
(
[type] = user
[name] = ali
[key] = #$WRE
[address] = {
)
<br></pre>
According to [address]
(im not good at english For this reason, there may be errors in the sentences)
please help me
You can use a regex like
'/(\w+)\s*=\s*"(.*?)"\s*(?=$|\w+\s*=)/ms'
See the regex demo
Pattern details:
The /s is a DOTALL modifier that makes the . match any symbol including a newline
The /m modifier makes $ match the end of the line
(\w+) - Group 1 capturing 1 or more alphanumeric or underscore characters
\s* - zero or more whitespaces
= - an equal sign
\s* - 0+ whitespaces
"(.*?)" - a double quote, zero or more any chars other than a newline as few as possible up to the first double quote and this quote as well (Group 2 is what is captured in between double quotes)
\s* - zero or more whitespaces
(?=$|\w+\s*=) -a positive lookahead requiring the end of string to appear right after the current position or one or more alphanumeric followed with zero or more whitespaces and an equal sign.

Categories