Guillaume Rebmann
Guillaume Rebmann

Reputation: 184

Why is preg_match() returning two elements in the matches array?

I get 2 results with preg_match and I don't understand why. This is my code:

$pattern = "\[precom\]([A-Za-z]|\(|\)|[0-9]|\s|\*)*\[\/precom\]";
$data = "[precom](homme) Cher monsieur $name[/precom] ";
preg_match("/" . $pattern . "/", $data, $m);
print_r($m);

This is the result:

Array ( [0] => [precom](homme) Cher monsieur *name[/precom] [1] => e ) 

Could anyone help me to find the problem please?

Upvotes: 0

Views: 71

Answers (2)

hsz
hsz

Reputation: 152304

You should not parse HTML (or BBCode, etc) with regex. Try with:

$input = '[precom](homme) Cher monsieur $name[/precom]';
$dom   = new DOMDocument();
$dom->loadHTML(str_replace(array('[', ']'), array('<', '>'), $input));
$output = $dom->textContent;

var_dump($output);

Output:

string '(homme) Cher monsieur $name' (length=27)

Upvotes: 4

Pinna_be
Pinna_be

Reputation: 4617

from http://www.php.net//manual/en/function.preg-match.php

matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

Upvotes: 2

Related Questions