Php regular expression/string to array problem

Hi there. I have a javascript code that packages an array as a string and sends it to a php mailer, which then separates the string into an array for mailing using a preg_split regular expression that searches for a comma followed by an html tag.

$myWrongArray = preg_split("/,(?=<)/",$myVar); // lookahead splits the string when the comma is before a tag (the opening bracket < )
//The look ahead is (?=<), which interrogates the next character and if it is the angle bracket, <, the preg_split function operates.

Everything works great EXCEPT when the string contains a degree sign or an &, in which case the array is returned up to the degree or & and then stops.

I can’t for the life of me understand it. Any ideas?

I have no idea why someone would think this was a good idea…

1 Like

hmmm, not the most helpful reply.

If you want to know…

the javascript program presents the viewer with as quiz and collects the questions asked in an array. It then marks and sends the results to the quizzee including the questions asked and answers given, with the correct answer.

That sounds like a JSON object, not a string with html embedded in it to me.

While I know you want to fix this specific problem, it sounds like the issue is much larger and needs to be addressed where it happens, not where it surfaces.

I think that the problem actually comes down to encoding of the php in the mail program. I am reading around and there are quite a few posts about problems with special characters.

My encoding seems OK, but one never knows:

$sendTo = $data7;
$subject = $data8." summary results for ".$data1;

$headers = “MIME-Version: 1.0”."\n";
$headers .= “Content-Type:text/html;charset=utf-8\r\n”;
$headers .= “bcc: $emailList\r\n”;
$headers .= “From: " . $data1. “<” . "[email protected]”.">\r\n";
// next include a reply to
$headers .= "Reply-To: " . $data7 . “\r\n”;
$headers .= "Return-path: " . $data7. “\r\n”;

// now we can add the content of the message to a body variable
$message = “”;
$message .= “Online test - “.$data8.””;
$message .= “

”.$data1.", you have attempted “.$data3. " questions”;

$message .= " in “.$data4.” minutes and “.$data5.” seconds";
$message .= " and scored a total of “.$data2.”.

";
$message .= "

Final percentage = “.$data6.”%

\r\n\r\n";
$message .= "

The following questions were answered incorrectly:


    ";

    foreach($myWrongArray as $my_Array){
    $message .= “\r\n\r\n

  • ”.$my_Array."
  • ";
    }
    $message .= “

”;
// finally, send the email
mail($sendTo, $subject, $message, $headers);
?>

Possible, but you are also showing that what I said is exactly what you are doing as well…

Systems that send mail must be capable of handling outgoing mail for all valid addresses. Contrary to the relevant standards, some defective systems treat certain legitimate addresses as invalid and fail to handle mail to these addresses. Hotmail, for example, refuses to send mail to any address containing any of the following standards-permissible characters: !#$%*/?^{|}~`

rfc5321

I am actually sending the emails to myself. But any message that contains a degree sign or ampersand is truncated.

So, for example, when the string is “the temperature is 30ºC today and the sun is shining”

The message that arrives is “the temperature is 30”

and the remainder is lost.

So are you sure the script is actually receiving the entire message to begin with?

I’m fairly sure, because when I ask php to send a plain text email all the symbols arrive with the rest.

Then I would try htmlentities() and see if it changes things. I have not seen php truncate anything after a bad character before

same result, only now the html markup appears in the posted message

OK, I have asked php to output the array as a text file and it seems that the array is arriving truncated from the javascript!

// ------------------------- using AJAX request ----------------------------//
function postIt() {
var http = new XMLHttpRequest();
var url = “…/mail/testSum.php”;
var params = “realname=”+myName+"&rightAnswers="+correct+"&percentageScore="+percentage+"&wrongArray="+wstore+"&asked="+numq+"&mins="+minutes+"&secs="+seconds+"&deliver="+destination+"&testName="+test;
http.open(“GET”, url+"?"+params, true);
http.onreadystatechange = function() { //Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(null);
}
// --------------------------------- end AJAX ------------------------------

If I alert the array (string) in Javascript I get:

1. How many moles of an ideal gas are in a volume of 195.2 dm3 with a temperature of 450 Kelvin and a pressure of 71.6 kPa ?

Answer = 3.74 mol

,

2. What is the temperature of an ideal gas in °C, if a 1.063 mol sample occupies a volume of 119.8 dm3 at a pressure of 74.9 kPa ?

Answer = 743 °C

,

3. What is the volume in cm3 of an ideal gas, if a 0.024 mol sample has a temperature of 574 °C at a pressure of 156.7 kPa ?

Answer = 1080 cm3

,

4. How many moles of an ideal gas are in a volume of 26.1 cm3 with a temperature of 490 °C and a pressure of 84.2 kPa ?

Answer = 0.35 mol

,

5. What is the pressure of an ideal gas in kPa ,if a 0.019 mol sample occupies a volume of 108.5 cm3 at a temperature of 567 °C ?

Answer = 1.22 kPa

You see that the degree signs are in there …

BUT the text file output from php reads:

Incorrectly answered:

1. How many moles of an ideal gas are in a volume of 195.2 dm3 with a temperature of 450 Kelvin and a pressure of 71.6 kPa ?

Answer = 3.74 mol

,

2. What is the temperature of an ideal gas in ,

The JavaScript is bad, you’re doing a get when you should do a post for one thing

You are actually where I was with PHP about 9 years ago. For your actual problem you should be using POST, that is easier to do with JQuery by the way, and you just need to serialize everything. However, from the looks of it, you are also identifying the correct answer, rather than validating it. Would you be interested in fixing the totality of issues, or just your primary concern?

html

<div id="response"></div>

<form id="quiz">
    <div>
    <p id="q1">
        1. What is the temperature of an ideal gas in °C, if a 1.063 mol sample occupies a volume of 119.8 dm3 at a pressure of 74.9 kPa?
    </p>
    <p>
        <input type="text" name="a1">
    </p>
    </div>


    <p><input type="button" id="submit" value="Submit"></p>
</form>

<script>

    $(document).ready(function(){
        $('#submit').on('click', function() {
            var form = $('form').serialize();

            $.post("processing.php", form, function(data, status){
                $('#response').html("Data: " + data + "\nStatus: " + status);
            });
        });
    });
</script>

Processing

<?php

// 743 °C

if($_SERVER['REQUEST_METHOD'] != 'POST')
    exit("Method not implemented");


print_r($_POST);

returns

Data: Array ( [a1] => 743 °C ) Status: success

I don’t know what you mean by “just need to serialize everything. However, from the looks of it, you are also identifying the correct answer, rather than validating it”.

The javascript generates questions for an HTML file that presents a quiz to a visitor. The js marks the quiz and then sends the questions, answers and marks back to the visitor.

I would rather not use jquery. I would like to identify the problem in the ajax.

I said what the problem was, it’s using get rather than a post. Get sends the data through the url and while I don’t know about the other special characters, I know ampersands are reserved for a special meaning.

OK, I changed the AJAX to post using jquery (I coiuldn’t find any vanilla solutions). Now my Array is sent to php correctly BUT the php is unpacking the array and leaving it with commas surrounded by inverted commas between the Array members.

The Array variable string arrives as:

$myVar=$_POST[“wrongArray”];

I then split the string up into another array using:

$myWrongArray = preg_split("/,(?=<)/",$myVar);

And process the array for printing in the email:

$message .="

    ";
    foreach($myWrongArray as $my_Array){
    $message .= “\r\n\r\n
  • ”.$my_Array."
  • ";
    $message .="
";
}

but my email looks like this:

["

1. What is the volume in dm3 of an ideal gas, if a 0.087 mol sample has a temperature of 350 Kelvin at a pressure of 206.4 kPa ?

Answer = 1.23 dm3
","

2. How many moles of an ideal gas are in a volume of 57.3 dm3 with a temperature of 206 Kelvin and a pressure of 55.7 kPa ?

Answer = 1.86 mol
","

3. What is the volume in dm3 of an ideal gas, if a 0.184 mol sample has a temperature of 368 Kelvin at a pressure of 58 kPa ?

Answer = 9.7 dm3
","

4. What is the pressure of an ideal gas in kPa ,if a 0.267 mol sample occupies a volume of 217 dm3 at a temperature of 429 Kelvin ?

Answer = 4.39 kPa
","

5. How many moles of an ideal gas are in a volume of 246.9 dm3 with a temperature of 701 Kelvin and a pressure of 93.2 kPa ?

Answer = 3.95 mol
","

6. What is the temperature of an ideal gas in Kelvin, if a 1.161 mol sample occupies a volume of 161.5 dm3 at a pressure of 123.2 kPa ?

Answer = 2062 Kelvin
"]

Notice the square brackets at the beginning and end, and the peculiar “,” between questions. Any ideas?

What is your current code? It isn’t PHP doing it, it’s how it is being passed in. But, we can fix that too.

This isn’t needed. You just need to learn how to deal with the objects coming in.

So, if you pass in a JSON object to PHP, you can then decode it and you have an associative array.

Sponsor our Newsletter | Privacy Policy | Terms of Service