2

I'm trying to learn regex in php. Why does this result in an array to string conversion error on the last line and how do I fix it?

$document = "{title}this is the title{/title}";
preg_match("/{title}(.*){\/title}/", $document, $match);

echo $match;
2
  • 2
    $match is an array, use print_r($match) Commented Jul 21, 2016 at 20:02
  • Also, for learning purposes, a useful tool for playing around with regex and how it will work with PHP is phpliveregex.com Commented Jul 21, 2016 at 20:11

1 Answer 1

1

See this demo:

$document = "{title}this is the title{/title}";
preg_match("/{title}(.*){\/title}/", $document, $match);
//echo $match; // PHP Notice:  Array to string conversion in /home/jxkaKh/prog.php on line 5
print_r($match);
// => Array(    [0] => {title}this is the title{/title}    [1] => this is the title)

See preg_match reference:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
...
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.

And your pattern contains a capture group defined as (.*).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.