Extracting all values between curly braces regex php
Do like this...
<?php
$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
preg_match_all('/{(.*?)}/', $content, $matches);
print_r(array_map('intval',$matches[1]));
OUTPUT :
Array
(
[0] => 123456
[1] => 7894560
[2] => 145789
)
Two compact solutions weren't mentioned:
(?<={)[^}]*(?=})
and
{\K[^}]*(?=})
These allow you to access the matches directly, without capture groups. For instance:
$regex = '/{\K[^}]*(?=})/m';
preg_match_all($regex, $yourstring, $matches);
// See all matches
print_r($matches[0]);
Explanation
- The
(?<={)
lookbehind asserts that what precedes is an opening brace. - In option 2,
{
matches the opening brace, then\K
tells the engine to abandon what was matched so far.\K
is available in Perl, PHP and R (which use thePCRE
engine), and Ruby 2.0+ - The
[^}]
negated character class represents one character that is not a closing brace, - and the
*
quantifier matches that zero or more times - The lookahead
(?=})
asserts that what follows is a closing brace.
Reference
- Lookahead and Lookbehind Zero-Length Assertions
- Mastering Lookahead and Lookbehind
DEMO :https://eval.in/84197
$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";
preg_match_all('/{(.*?)}/', $content, $matches);
foreach ($matches[1] as $a ){
echo $a." ";
}
Output:
123456 7894560 145789