How to match all @__('...') on string in php regex?

Member

by mac , in category: PHP General , 5 months ago

How to match all @__('...') on string in php regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 5 months ago

@mac 

To match all occurrences of @__('...') in a string using PHP regex, you can use the preg_match_all function. Here is an example code:

1
2
3
4
5
6
$string = "This is a sample string with @__('example1') and @__('example2')";

preg_match_all('/@__('(.*?)')/', $string, $matches);

// The matches array will contain all the matches
print_r($matches[0]);


In the above code, the regex pattern is /@__('(.*?)')/:

  • @__ matches '@__' literally.
  • (' matches the opening parenthesis and single quote.
  • (.*?) matches any characters (non-greedy) between the single quotes and captures it as a group.
  • ') matches the closing single quote and parenthesis.


The captured matches are stored in the $matches array, where $matches[0] contains all the exact matches found in the string.


Running the above code will output:

1
2
3
4
5
Array
(
    [0] => @__('example1')
    [1] => @__('example2')
)


Now, you can access individual matches or iterate over the array to perform further actions with each match.