Sometime we has situation  where we need to find string between script tag, i was wondering for the solution for this and  found this. consider below code is enclosed in script tag.

 $string  = ' 
              myData = {"fname": "John", "lname": "Bob", 
                         "fruits": {
                                     "mango": true, 
                                     "apple": true, 
                                     "orange": true} 
                        };
           ';
 //Required output : myData = {"fname": "John", "lname": "Bob", "fruits": {"mango": true, "apple": true, "orange": true} };

 

we can do this by two way one using regular expression and other by PHP :

preg_match('~]*>(.*?)]*>~', $string, $results)

//The array $results[1] will have required string.


//By OR PHP :


function search_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}

$key_string = ‘ text you want to get return ‘;
$required_string = search_string_between($key_string, ”, ”);

echo $required_string;

//Required output : myData = {“fname”: “John”, “lname”: “Bob”, “fruits”: {“mango”: true, “apple”: true, “orange”: true} };

Advertisements