Extracting A Substring That Is Wrapped By Some Characters
What is best practice to select content between a pair of delimiter using regular expression excluding the delimiters in PHP and JS? aassssd [dddd] fff ffff (delimiter=[..]) outp
Solution 1:
I would use the non-greedy .*?
which captures everything upto the end delimiter :
$str = 'aassssd QddddQ fff ffff';
preg_match_all('/[Q](.*?)[Q]/', $str, $out, PREG_PATTERN_ORDER);
var_dump($out);
produces :
Array
(
[0] => Array
(
[0] => QddddQ
)
[1] => Array
(
[0] => dddd
)
)
You would need to escape the [
and ]
delimiters : /[\[](.*?)[\]]/
This uses a single capture group (.*?)
so the output you need is in position 1 in the output array.
Solution 2:
aassssd [dddd] fff ffff (delimiter=[..]) output -> dddd
RegEx for PHP:
(?<=\[).*?(?=\])
RegEx for JS (works in PHP too):
[^\[]*?(?=\])
Post a Comment for "Extracting A Substring That Is Wrapped By Some Characters"