0

I'm weak with regex, need help. My problem is I have to extract all the string that matches the given pattern I have into an array. See the problem below:

The string

<?php
$alert_types = array(
    'warning' => array('', __l("Warning!") ),
    'error' => array('alert-error', __l("Error!") ),
    'success' => array('alert-success', __l("Success!") ),
    'info' => array('alert-info', __l("For your information.") ),
);?>

The Preg_Match Code

preg_match("/.*[_][_][l][\(]['\"](.*)['\"][\)].*/", $content, $matches);

I'm only getting the first one match which is Warning!. I'm Expecting matches will have the following values:

Warning!, Error!, Success!, For your information.

Actually I'm using file_get_contents($file) to get the string.

Can anyone help me to solve this. Thankyou in advance.

Oswald
  • 31,254
  • 3
  • 43
  • 68
lukaserat
  • 4,768
  • 1
  • 25
  • 36
  • sorry guys, I should used preg_match_all instead of preg_match – lukaserat Oct 25 '13 at 01:19
  • @mario yeah you're right. I've also solved the problem without looking on that possible duplicate. :) here's my regex: preg_match_all("|__l\(['\"](.*)['\"]\)|", $content, $matches, PREG_PATTERN_ORDER); incase for those interested. – lukaserat Oct 25 '13 at 01:21

1 Answers1

2

preg_match() only finds the first match in the string. Use preg_match_all() to get all matches.

preg_match_all("/.*__l\(['\"](.*?)['\"]\).*/", $content, $matches);

$matches[1] will contain an array of the strings you're looking for.

BTW, you don't need all those single-character brackets. Just put the character into the regexp.

var_dump($matches);

array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(45) "    'warning' => array('', __l("Warning!") ),"
    [1]=>
    string(52) "    'error' => array('alert-error', __l("Error!") ),"
    [2]=>
    string(58) "    'success' => array('alert-success', __l("Success!") ),"
    [3]=>
    string(65) "    'info' => array('alert-info', __l("For your information.") ),"
  }
  [1]=>
  array(4) {
    [0]=>
    string(8) "Warning!"
    [1]=>
    string(6) "Error!"
    [2]=>
    string(8) "Success!"
    [3]=>
    string(21) "For your information."
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612