Saeid Khaleghi
Saeid Khaleghi

Reputation: 175

PHP : Matching strings between two strings

i have a problem with preg_match , i cant figure it out.

let the code say it :

function::wp_statistics_useronline::end
function::wp_statistics_visitor|today::end
function::wp_statistics_visitor|yesterday::end
function::wp_statistics_visitor|week::end
function::wp_statistics_visitor|month::end
function::wp_statistics_visitor|total::end

these are some string that run functions inside php;

when i use just one function::*::end it works just fine. but when it contain more than one function , not working the way i want it parse the match like :

function::wp_statistics_useronline::end function::wp_statistics_visitor|today::end AND ....::end

so basically i need Regex code that separate them and give me an array for each function::*::end

Upvotes: 0

Views: 60

Answers (3)

Michael Mikhjian
Michael Mikhjian

Reputation: 2794

This is what you're looking for:

function\:\:(.*?)\:

Make sure you have the dot matches all identifier set.

After you get the matches, run it through a forloop and run an explode on "|", push it to an array and boom goes the dynamite, you've got what you're looking for.

Upvotes: 0

hakre
hakre

Reputation: 197767

It's pretty straight forward:

$result = preg_match_all('~function::(\S*)::end~m', $subject, $matches) 
          ? $matches[1] : [];

Which gives:

Array
(
    [0] => wp_statistics_useronline
    [1] => wp_statistics_visitor|today
    [2] => wp_statistics_visitor|yesterday
    [3] => wp_statistics_visitor|week
    [4] => wp_statistics_visitor|month
    [5] => wp_statistics_visitor|total
)

And (for the second example):

Array
(
    [0] => wp_statistics_useronline
    [1] => wp_statistics_visitor|today
)

The regex in the example is a matching group around the part in the middle which does not contain whitespace. So \S* is a good fit.

As the matching group is the first one, you can retrieve it with $matches[1] as it's done after running the regular expression.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

I assume you were actually using function::(.*)::end since function::*::end is never going to work (it can only match strings like "function::::::end").

The reason your regex failed with multiple matches on the same line is that the quantifier * is greedy by default, matching as many characters as possible. You need to make it lazy: function::(.*?)::end

Upvotes: 1

Related Questions