Bert
Bert

Reputation: 855

preg_match returns identical elements only once

I am going through a string and proces all the elements between !-- and --!. But only unique elements are processes. When I have !--example--! and a bit further in the text also !--example--!, the second one is ignored.

This is the code:

while ($do = preg_match("/!--(.*?)--!/", $formtext, $matches)){

I know about preg_match_all, but need to do this with preg_match.

Any help? Thanks in advance!

Upvotes: 2

Views: 1274

Answers (3)

Wrikken
Wrikken

Reputation: 70460

Use preg_match_all

edit: some clarification yields:

$string = '!--example--!   asdasd !--example--!';
//either this:
$array = preg_split("/!--(.*?)--!/",$string,-1,PREG_SPLIT_DELIM_CAPTURE);
var_dump($array);
array(5) {
  [0]=>
  string(0) ""
  [1]=>
  string(7) "example"
  [2]=>
  string(10) "   asdasd "
  [3]=>
  string(7) "example"
  [4]=>
  string(0) ""
}

//or this:
$array = preg_split("/(!--(.*?)--!)/",$string,-1,PREG_SPLIT_DELIM_CAPTURE);
var_dump($array);

array(7) {
  [0]=>
  string(0) ""
  [1]=>
  string(13) "!--example--!"
  [2]=>
  string(7) "example"
  [3]=>
  string(10) "   asdasd "
  [4]=>
  string(13) "!--example--!"
  [5]=>
  string(7) "example"
  [6]=>
  string(0) ""
}

Upvotes: 3

Søren Løvborg
Søren Løvborg

Reputation: 8751

You'll want PHP to look for matches only after the previous match. For that, you'll need to capture string offsets using the PREG_OFFSET_CAPTURE flag.

Example:

$offset = 0;
while (preg_match("/!--(.*?)--!/", $formtext, $match, PREG_OFFSET_CAPTURE, $offset))
{
    // calculate next offset
    $offset = $match[0][1] + strlen($match[0][0]);

    // the parenthesis text is accessed like this:
    $paren = $match[1][0];
}

See the preg_match documentation for more info.

Upvotes: 4

user876978
user876978

Reputation: 1

while ($do = preg_match("/[!--(.*?)--!]*/", $formtext, $matches)){

Specify the * at the end of the pattern to specify more than one. They should both get added to your $matches array.

Upvotes: 0

Related Questions