0

How do I use preg_match to return an array of all substrings that match (:)?

For example if I have a string that is:

My name is (:name), my dog's name is (:dogname)

I want to use preg_match to return

array("name", "dogname");

I tried using this expression...

preg_match("/\(:(?P<var>\w+)\)/", $string, $temp);

But it only returns the first match.

Can anyone help me?

Rain
  • 309
  • 1
  • 6
  • 11

3 Answers3

3

First off, you want preg_match_all (find all matches), not preg_match (check if there are any matches at all).

And for the actual regex, the best technique is to search for (: and then search for any character except for )

$string = "My name is (:name), my dog's name is (:dogname)";

$foundMatches = preg_match_all('/\(:([^)]+)\)/', $string, $matches);
$matches = $foundMatches ? $matches[1] : array(); // get all matches for the 1st set of parenthesis. or if there were no matches, just an empty array

var_dump($matches);
Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
2

This should help you :)

$s = "My name is (:name), my dog's name is (:dogname)";
$preg = '/\(:(.*?)\)/';
echo '<pre>';
preg_match_all($preg, $s, $matches);
var_dump($matches);
androidavid
  • 1,258
  • 1
  • 11
  • 20
1

From the documentation for preg_match:

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Hamish
  • 22,860
  • 8
  • 53
  • 67