John R
John R

Reputation: 3036

Simplify PHP code and Regex

I could use some help simplifying the following code that includes a regex statement. I am simply trying to get the integers from all possible substrings contained in a larger text and then push those integers onto an array. I know I should not have to use split, but I forget how to do do it with regex.

    preg_match_all('/bar:foo\(?[0-9]*\);/', $in , $tag);
    for ($i = 0; $i < count($tag[0]); $i++) {
        $parts = explode("(", $tag[0][$i]);           
        $parts2 = explode(")", $parts[1]);
        array_push($myArr, $parts2[0]);
    }

Upvotes: 0

Views: 87

Answers (2)

hakre
hakre

Reputation: 198119

Actually, you might not need to use preg_split, but you can already improve it by modifying your current pattern:

$numbers = preg_match_all('/bar:foo\(?([0-9]*)\);/', $in , $matches) 
           ? array_map('intval', $matches[1])
           : array();

Upvotes: 3

safarov
safarov

Reputation: 7804

preg_match_all('/bar:foo\(?([0-9]*)\);/', $in , $tags);
print_r($tags);

Upvotes: 1

Related Questions