Ekky
Ekky

Reputation: 790

Want to match the pattern in php

I want to match pattern for the below string: (String is dynamic means i am getting it in request from html form, so it may be new every time but format of string will always same)

Actually i want that keywords(name,salary,account) that may be different in every request

$str="$(name) is $(salary) and $(account)";
if(preg_match_all("/\$\((.+?)\)/is",$str,$arrmsgvar,PREG_SET_ORDER)){
    echo "<pre>";
    print_r($arrmsgvar);
    echo "</pre>";
}

I am writing regex to match that pattern but not getting successful. would anyone please tell me the right regex for above code?

Upvotes: 3

Views: 110

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173582

Your regular expression (and search string too if you want to be sure) should be in single quotes.

With double quotes, PHP interprets your regular expression as this:

/$\((.+?)\)/
 ^
missing backslash here

This code should work just fine.

<?php

$str='$(name) is $(salary) and $(account)';
if(preg_match_all('/\$\((.+?)\)/',$str,$arrmsgvar,PREG_SET_ORDER)){
    echo "<pre>";
    print_r($arrmsgvar);
    echo "</pre>";
}

Proof

Upvotes: 3

fullybaked
fullybaked

Reputation: 4127

This regex will return an array with the three values

"/\$\((\w+)\)/"

preg_match_all("/\$\((\w+)\)/",$str,$arrmsgvar);

Array
(
[0] => Array
    (
        [0] => $(name)
        [1] => $(salary)
        [2] => $(account)
    )

[1] => Array
    (
        [0] => name
        [1] => salary
        [2] => account
    )

)

Upvotes: 0

Related Questions