Search code examples
phpregexpreg-match

Need Help About php preg_match


I have a string:

access":"YOU HAVE 0 BALANCE","machine

How can I extract the string in between the double quotes and have only the text (without the double quotes):

YOU HAVE 0 BALANCE 

I have tried

if(preg_match("'access":"(.*?)","machine'", $tok2, $matches)){

but with no luck :( .


Solution

  • You may use

    '/access":"(.*?)","machine/'
    

    See the regex demo. The value you need is in Group 1.

    Details

    • access":" - a literal substring
    • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible, since *? is a lazy quantifier
    • ","machine - a literal substring

    See the PHP online demo:

    $re = '/access":"(.*?)","machine/';
    $str = 'access":"YOU HAVE 0 BALANCE","machine';
    if (preg_match($re, $str, $matches)) {
      print_r($matches[1]);
    }
    // => YOU HAVE 0 BALANCE