How to get a phone from the line?

$pp = "{ error:{code:0,text:'no'} , on_data : 1, data : {'phone':'+7 906 888-85-02 '} }"; preg_match('/\'phone\':\'(\d+)\'/iU', $pp, $t); echo $t[1]; 
  • You only have numbers or all contents with characters + spaces with hyphens, i.e. +7 906 ....? if all that \'phone\':\'(.*?)\' - Tunker
  • Where do you get such a json curve? - splash58
  • And why it was impossible to use json to parse the line and pull out the phone? - gil9red
  • Unfortunately, this is not json - andreymal

3 answers 3

Option 1

If it is JSON, use the PHP JSON built-in parser. Read more: http://php.net/manual/ru/function.json-decode.php

Option 2

Use an expression like this:

 'phone':'([^']+) 

PS in your JSON value of the phone field ends with a space. Make trim() after applying regex.

Use this site to check your regular expressions if you are not sure that they work correctly.

    Another option:

     preg_match('/\+7 [^\']+/', $your_string, $matches); echo trim($matches[0]); 

    And a good interactive tutorial: http://regexone.com/

      Just for fun

      The text in question is not JSON, but just a piece of JavaScript code.
      You can use the PEAR extension V8JS:

       $v8 = new V8Js(); $pp = "{ error:{code:0,text:'no'} , on_data : 1, data : {'phone':'+7 906 888-85-02 '} }"; $js = "var x = ".$pp.";print(x.data.phone);"; var_dump( $v8->executeString( $js, 'basic.js' ) ); 

      Result var_dump :

       +7 906 888-85-02 int(17) 

      The returned number 17 is the length of the string.