17

I have content in this form

$content ="<p>This is a sample text where {123456} and {7894560} ['These are samples']{145789}</p>";

I need all the values between curly braces in an array like the one shown below:

array("0"=>"123456","1"=>"7894560","2"=>"145789")

I tried with this code:

<?php
preg_match_all("/\{.*}\/s", $content, $matches);
?>

But I am getting in here values from first curly brace to the last found in the content. What can be done to get the array in above format? I knew that the pattern I have used is wrong. What shall be given to get desired output shown above?

Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67
  • 1
    [Similar question](http://stackoverflow.com/q/20582312/1578604). The only difference could be that you have 1 brace instead of 2, but the principle remains the same. The main issue is that `.*` is greedy. Almost all the answers on that question tackle that issue. – Jerry Dec 30 '13 at 11:33

3 Answers3

28

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
)
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
21

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 the PCRE 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

zx81
  • 41,100
  • 9
  • 89
  • 105
4

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 
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53