Finding data inside quotes with regex php and json data

Post Reply
darknkreepy3#
Site Admin
Posts: 247
Joined: Tue Oct 27, 2009 9:33 pm

Finding data inside quotes with regex php and json data

Post by darknkreepy3# »

It was confusing that preg_match held not the array answer of each quoted area inside nodes starting in [0][1][2] but had the full answer in node [0]. It makes sense for debugging and further nesting of regex expressions now. Remember, even when finding one quote in a line of text, there will still be a regex match with the answer with[0] quotes and then without[1].

Code: Select all

$str1='Can you find the "quoted words" in this string...';

Sure.
A few examples that do the same thing are here along with the [0][1] match output

Code: Select all

$pattern='/"([^"]+)"/';

Code: Select all

$pattern='/"(.*?)"/';

Code: Select all

preg_match($pattern,$str1,$arr0);
$tempStr.="<h3>[0]".$arr0[0]." [1]".$arr0[1]."</h3>";
echo $tempStr;
A great example you can take apart I wrote to demonstrate the array structure of preg_match

Code: Select all

<?php
	/*
	02-21-2013
	php stores not an array of answers in sequence
	but the full answer in node 0, then nodes 1,2,3... are the needed 
	*/
	
	/*
	string "{data}" {} from JSON output
	{"....":"~~","....":"~~"} (,)
	[0][1] "....":"~~" (:)
	[0][1] .... ~~
	regex[0] "...." [1] .... 
	regex[0] "~~" [1] ~~ 
	*/
	$tStr='{"farenheit":"25","celsius":"-4"}';
	$arrA=explode(",",$tStr);//break data into an array with comma as delimiter ,
	$lenA=count($arrA);
	$tempStr="Today's temps<br />";
	
	//
	for($a=0;$a<$lenA;$a++)
		{
		$arrB=explode(":",$arrA[$a]);//break apart array into a reused temp array with : as delimiter
		$pattern='/"(.*?)"/';//find all quotes with info inbetween

		preg_match($pattern,$arrB[0],$arr0);//pattern,data,output
		preg_match($pattern,$arrB[1],$arr1);
		$tempStr.="<h3>".$arr1[0]."° ".$arr0[0]."</h3>";//anwers with full quotes as found items 
		$tempStr.="<h3>".$arr1[1]."° ".$arr0[1]."</h3>";//properly formatted found items without quotes
		}
	
	echo $tempStr;
	
	$pattern='/"([^"]+)"/';
	$nStr='hello there "friend" how are you';
	preg_match($pattern,$nStr,$arr2);
	$lenA=count($arr2);//[0]full [1]formatted [0]"friend" [1]friend
	//
	for($a=0;$a<$lenA;$a++)
		{
		echo "<h3>".$arr2[$a]."</h3>";
		}
?>
Post Reply