How to extract text between quotes containing a specific word? - php

The text between the quotes I am trying to extract, also has quotes within the text, like this: "data":"value"
The specific word is "data". The "value" will always be different. Once extracted it should be "data":"value" with the quotes.
So far...
<?
$dat = "file.dat";
$text = file_get_contents($dat);
$res = preg_match_all ('/"([^"]*)"/', $text, $matches);
if ($res) {
foreach (array_unique ($matches[0]) as $data) {
echo "$data";
}
}
else {
echo "No Data Found.";
}
My code just extracts any and all words between double quotes. How do I accomplish what I am trying to do? Thank you in advance.

As in the comments noticed. The format you are trying to parse is JSON and PHP comes with a easy to use function to parse JSON. You could try this:
<?
$dat = "file.dat";
$text = file_get_contents($dat);
$res = json_decode($text, true);
if ($res) {
foreach ($res as $key => $value) {
echo "$key => $value";
}
}
else {
echo "No Data Found.";
}
Untested, but should get the job done.

Related

Multiple preg_match_all result in foreach

I would like to replace each decimal number for later using in Javascript. so This is my code:
if (preg_match_all("#[0-9]+(\.[0-9]{1,8})#", $operationvalue_new2, $result)) {
foreach ($result[0] as $number_element) {
$operationvalue_new2 = preg_replace(
"#[0-9]+(\.[0-9]{1,8})#",
"Number(\\0)",
$operationvalue_new2
);
#echo $operationvalue_new2;
}
};
Here is an example what happens:
//var1812/100*(var1805*var1807*2.688)+(var1808-var1812)*var1806*var1807*1.2/100)
will be converted to
//var1812/100*(var1805*var1807*Number(Number(2.688)))+(var1808-var1812)*var1806*var1807*Number(Number(1.2))/100)
but should be
//var1818=var1812/100*(var1805*var1807*Number(2.688))+(var1808-var1812)*var1806*var1807*Number(1.2)/100)
Try this:
<?php
$subject = "var1812/100*(var1805*var1807*2.688)+(var1808-var1812)*var1806*var1807*1.2/100)";
$result = preg_replace('/([0-9]+\.[0-9]{1,8})/s', 'number($1)', $subject);
echo $result;
?>
Results in:
var1812/100*(var1805*var1807*number(2.688))+(var1808-var1812)*var1806*var1807*number(1.2)/100)

'Array' showing in my foreach loop

For some reason I'm getting the word 'array' as an output when I try to do a foreach to echo out the values in an array (there are 2 values). These show fine if I use print_r in the array so I know they are there. I've also tried using as list but that only shows the first value and nothing after it.
It's getting late so it might be something pretty silly! Thanks in advance
<?php
$crawl_url = "./emails.php";
function get_email($url) {
$input = #file_get_contents($url);
$regexp = '/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i';
preg_match_all($regexp, $input, $matches);
if (empty($input)) {
echo "No email addresses found";
}
else {
foreach($matches as $matches_values) {
print $matches_values;
}
}
}
get_email($crawl_url);
echo '<br /> function complete';
?>
I think you're missing the 0 index on $matches.
Try this :
foreach($matches[0] as $matches_values) {
print $matches_values;
}

echo text separating every 3 words per line?

I have seen some samples using var_dump, but I I would rather use a simple echo, if it's possible.
It should look like this using echo:
This is a
simple text
I just wrote
Using var_dump:
function split3($text)
{
$array = array();
foreach(explode(' ',$text) as $i=>$word)
{
if($i%3) {
$array[floor($i/3)] .= ' '.$word;
} else {
$array[$i/3] = $word;
}
}
return $array;
}
$text = "This is a simple text I just wrote";
var_dump(split3($text));
Your sample output is a bit wrong compare to your question.
If the output is like this.
This is a
simple text I
just wrote
Then replace the var_dump(split3($text)); with this
$splitedText = split3($text);
foreach($splitedText as $value){ //Just print the array content
echo $value . "<br />"; //I use <br /> as a new line
}

PHP: $_POST array to XML file and display results

I'm creating a "Madlibs" page where visitors can create funny story things online. The original files are in XML format with the blanks enclosed in XML tags
(Such as blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb> ).
The form data is created using XSL and the results are saved using a $_POST array. How do I post the $_POST array between the matching XML tags and then display the result to the page? I'm sure it uses a "foreach" statement, but I'm just not familiar enough with PHP to figure out what functions to use. Any help would be great.
Thanks,
E
I'm not sure if I understood your problem quite well, but I think this might help:
// mocking some $_POST variables
$_POST['Verb'] = 'spam';
$_POST['PluralNoun'] = 'eggs';
// original template with blanks (should be loaded from a valid XML file)
$xml = 'blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb>';
$valid_xml = '<?xml version="1.0"?><xml>' . $xml . '</xml>';
$doc = DOMDocument::loadXML($valid_xml, LIBXML_NOERROR);
if ($doc !== FALSE) {
$text = ''; // used to accumulate output while walking XML tree
foreach ($doc->documentElement->childNodes as $child) {
if ($child->nodeType == XML_TEXT_NODE) { // keep text nodes
$text .= $child->wholeText;
} else if (array_key_exists($child->tagName, $_POST)) {
// replace nodes whose tag matches a POST variable
$text .= $_POST[$child->tagName];
} else { // keep other nodes
$text .= $doc->saveXML($child);
}
}
echo $text . "\n";
} else {
echo "Failed to parse XML\n";
}
Here is PHP foreach syntax. Hope it helps
$arr = array('fruit1' => 'apple', 'fruit2' => 'orange');
foreach ($arr as $key => $val) {
echo "$key = $val\n";
}
and here is the code to loop thru your $_POST variables:
foreach ($_POST as $key => $val) {
echo "$key = $val\n";
// then you can fill each POST var to your XML
// maybe you want to use PHP str_replace function too
}

White Space in Key of Associative Array PHP

I'm parsing out an HTML table and building an array based on the row values. My problem is the associative keys that are returned have a bit of white space at the end of them giving me results like this:
Array ( [Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57) )
So a line like this:
echo $myArray['Count'];
or
echo $myArray['Count '];
Gives me a blank result.
for now I've got a pretty hacky work around going...
foreach($myArray as $row){
$count = 0;
foreach($row as $info){
if($count == 0){
echo 'Count:' . $info;
echo '<br>';
}
if($count == 1){
echo ' Class:' . $info;
echo '<br>';
}
if($count == 2){
echo ' Description:' . $info;
echo '<br>';
}
$count++;
}
}
The function I'm using to parse the table I found here:
function parseTable($html)
{
// Find the table
preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);
// Get title for each row
preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
$row_headers = $matches[1];
// Iterate each row
preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);
$table = array();
foreach($matches[1] as $row_html)
{
preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
$row = array();
for($i=0; $i<count($td_matches[1]); $i++)
{
$td = strip_tags(html_entity_decode($td_matches[1][$i]));
$row[$row_headers[$i]] = $td;
}
if(count($row) > 0)
$table[] = $row;
}
return $table;
}
I'm assuming I can eliminate the white space by updating with the correct regex expression, but, of course I avoid regex like the plague. Any ideas? Thanks in advance.
-J
You can use trim to remove leading and trailing whitespace characters:
$row[trim($row_headers[$i])] = $td;
But don’t use regular expressions for parsing the HTML document; use a proper HTML parser like the Simple HTML DOM Parser or the one of DOMDocument instead.
An easy solution would be to change
$row[$row_headers[$i]] = $td;
to:
$row[trim($row_headers[$i])] = $td;

Categories