Endline after certain number of characters - php

I have a text file with a lot of inserts that looks like this:
INSERT INTO yyy VALUES ('1','123123','da,sdadwa','6.7','24f,5','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','dasdasd','q231e','','0','','g','1','123123','dasdadwa','6.7','24f,5','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','0','','a','1','123123','dasdadwa','655.755','24f,5','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','','','a');
INSERT INTO yyy VALUES ('2','123123','dasdadwa','6.8','24f,6','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','dasdasd','q231e','','0','','g','2','123123','dasdadwa','6.8','24f,6','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','0','','a','2','123123','dasdadwa','6.8','24f,6','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','','','a');
INSERT INTO yyy VALUES ('3','123123','dasdadwa','6.9','24f,7','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','dasdasd','q231e','','0','','g','3','123123','dasdadwa','6.9','24f,7','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','0','','a','3','123123','dasdadwa','6.9','24f,7','f5,5','dasdad,fsdfsdfsfsasada dasdasd','','','q231e','','','','a');
INSERT INTO yyy VALUES ('4','123123','dasdadwa','6.10','24f,8','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','dasdasd','q231e','','0','','g','4','123123','dasdadwa','6.10','24f,8','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','','q231e','','0','','a','4','123123','dasdadwa','6.10','24f,8','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','','q231e','','','','a');
INSERT INTO yyy VALUES ('5','123123','dasdadwa','6.11','24f,9','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','dasdasd','q231e','','0','','g','5','123123','dasdadwa','6.11','24f,9','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','','q231e','','0','','a','5','123123','dasdadwa','6.11','24f,9','f5,5','dasdad,fsdfsdfsfsasada dasdasd','aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','','q231e','','','','a');
I must modify this text file so that each line can have a maximum of 50 characters. The problem is that I cannot simply put an endline after 50 characters because that would break the elements in those inserts, so I need to put the endline before the last comma.
For the first row it needs to be something like this:
INSERT INTO yyy VALUES ('1','123123','da,sdadwa',
'6.7','24f,5','f5,5',
'dasdad,fsdfsdfsfsasada dasdasd',
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'dasdasd','q231e','','0','','g','1','123123',
'dasdadwa','6.7','24f,5','f5,5',
'dasdad,fsdfsdfsfsasada dasdasd','','','q231e','',
'0','','a','1','123123','dasdadwa','655.755',
'24f,5','f5,5','dasdad,fsdfsdfsfsasada dasdasd',
'','','q231e','','','','a');
As you can see there can be commas even inside the elements('da,sdadwa') which makes this a tad more difficult. I tried putting everything into arrays but I ran into some problems and couldn't get it to work.
What i tried:
if(is_array($testFileContents))
{
foreach($testFileContents as $line)
{
$j=0;
for($i=0;$i<=strlen($line);$i++)
{
//echo $line[$i];
$ct=1;
if($j==50)
{
if($line[$j]==",")
{
//$line[$j]=$line[$j].PHP_EOL;
}
else
{
$temporaryJ = $j;
while($line[$temporaryJ]!=",")
{
$temporaryJ--;
}
//$line[$temporaryJ] = $line[$temporaryJ].PHP_EOL;
//$j=$i-$ct*50;
$j=0;
$ct=$ct+1;
echo $ct." ";
}
}
else
{
$j++;
}
}
}
}
I know there has to be a much more simple way of going around this without using arrays but I cannot figure it out.

You can use preg_split() to split the lines. I found a pattern another user posted in this answer for matching values for an INSERT statement:
"~'(?:\\\\'|[^'])*'(*SKIP)(*F)|,~". This utilizes Special Backtracking Control Verbs.
You can play with the PHP code in this PhpFiddle.
foreach($lines as $line) {
$matches = preg_split("~'(?:\\\\'|[^'])*'(*SKIP)(*F)|,~",$line);
$currentIndex = 0;
$currentLine = '';
$outputLines = array();
$delimeter = ',';
while($currentIndex < count($matches)) {
if ($currentIndex == count($matches)-1 ) {
$delimeter = '';
}
$tempLine = $currentLine . $matches[$currentIndex] . $delimeter;
if (strlen($tempLine) <= 50) {
$currentLine .= $matches[$currentIndex] . $delimeter;
}
else {//push current line into array and start a new line
$outputLines[] = $currentLine;
$currentLine = $matches[$currentIndex] . $delimeter;
}
if ($currentIndex == count($matches)-1 ) {
$outputLines[] = $currentLine;
}
$currentIndex++;
}
//can use implode("\n",$outputLines) to write out to file
//or whatever your needs are
}

Related

How to continuously push user input data into $_SESSION array and then retrieve it?

I am trying to get my head around the way PHP sessions work. I am simply trying a hangman game where the first player inputs a secret word, a second player then starts to guess one letter at a time.
Let's says that the secret word is cat, player two tries, c then a then s. I would like the final output to be c a _.
<?php
session_start();
global $word;
global $guess;
global $hangman;
if (isset($_POST['player1'], $_POST['word'])) {
$_SESSION['word'] = $_POST['word'];
$word = $_SESSION['word'];
}
if (isset($_POST['player2'], $_POST['guess'])) {
$_SESSION['guess'] = $_POST['guess'];
$guess = $_SESSION['guess'];
}
$counter = 0;
$word = strtolower($_SESSION['word']);
$guess = strtolower($_SESSION['guess']);
echo $word . "<br>";
$found = [];
$counter = 0;
for ($i = 0; $i < strlen($word); $i++) {
if ($counter < strlen($word)) {
if (strpos($word[$i], $guess) !== false) {
$found[] = $guess;
$counter++;
} else {
$found[] = " _ ";
}
}
}
print_r($found);
Instead of printing out all the contents the found array, I am only getting one single letter to print every time. However, I would like to see the full concatenated string as I've mentioned above.
Here is what the output looks like:
How to continuously push user input data into $_SESSION array and then retrieve it?
An easy way to do that is by binding a variable with an element in the $_SESSION array.
This is a useful trick that you won't find in the manual.
A simple example:
$foo =& $_SESSION['foo'];
That assignment will bind $foo and $_SESSION['foo'] to the same value,
so every update to $foo is also an update to $_SESSION['foo'].
Here is an example usage in the style of your hangman game:
<?php
session_start();
$word =& $_SESSION['word']; //bind $word with $_SESSION['word']
$found =& $_SESSION['found']; //bind $found with $_SESSION['found']
if (isset($_REQUEST['word'])) {
$word = str_split($_REQUEST['word']);
$found = array_fill(0, count($word), '_');
}
if (isset($_REQUEST['guess'], $word, $found)) {
$guess = array_fill(0, count($word), $_REQUEST['guess']);
$found = array_replace($found, array_intersect($word, $guess));
}
echo join(' ', $found);
With the binding, the values of $word and $found will be saved as a part of the session data,
without the need to do $_SESSION['word'] = $word; and $_SESSION['found'] = $found; anywhere in the script.
Note that I use $_REQUEST instead of $_POST to make it easier to test with a browser.
Modify as desired.
Make the $found as a string variable.Instead of pushing in $found[] ,concatenate $guess Like $found .= $guess;
You should save what was already found between requests, since now you are just searching the $_SESSION['word'] for the char in the last request.
if ( isset($_POST['player1']) && !empty($_POST['word']) ) {
$_SESSION['word'] = str_split( $_POST['word'] );
// ceate empty array for storing the already found chars
$_SESSION['found'] = str_split( str_repeat( " ", strlen($_POST['word']) ) );
}
if ( isset($_POST['player2']) && !empty($_POST['guess']) ) {
array_walk( $_SESSION['word'], function( $v, $k ) {
if ( $v == $_POST['guess'] )
$_SESSION['found'][$k] = $v;
});
}
if ( $_SESSION['word'] == $_SESSION['found'] )
echo 'Game Over';
print_r( $_SESSION['found'] );
You are overwriting your $_SESSION['guess'] with:
$_SESSION['guess'] = $_POST['guess'];
on every submission.
I would recommend that you store your posted guesses as a subarray of letters like:
$_SESSION['guesses'][] = $_POST['guess'];
Then you will never overwrite earlier guesses.
This will mean you will have a session array with this type of structure:
$_SESSION=[
'player1' => 'me',
'word' => 'cat',
'player2' => 'myself',
'guesses' => ['a','c']
];
From here, you can call str_split() on $_SESSION['word'] and check for found/remaining letters using $_SESSION['guesses'] and array comparison functions.
Here are some untested portions of code that may help you along...
session_start();
if (!isset($_SESSION['player1'], $_SESSION['word'])) { // no stored player1 or word
if (!isset($_POST['player1'], $_POST['word'])) { // no posted player1 or word
// show form with player1 and word fields
} else {
$_SESSION=['player1'=>$_POST['player1'],'word'=>strtolower($_POST['word'])]; // store player1 and word
}
} elseif (!isset($_SESSION['player2'], $_SESSION['guesses'])){ // no stored player2 or guesses
if (!isset($_POST['player2'], $_POST['guess'])) { // no posted player2 or guess
// show form with player2 and first guess
} else {
$_SESSION['player2'] = $_POST['player1']; // store player2
$_SESSION['guesses'] = [strtolower($_POST['guess'])]; // store guessed character as first element of subarray
}
} elseif (isset($_POST['guess'])) {
$_SESSION['guesses'][] = strtolower($_POST['guess']); // store guessed character
}
And further down script here are some pieces...
$secret_letters=array_unique(str_split($_SESSION['word'])); // unique secret word letters
$found_letters=array_intersect($secret_letters,$_SESSION['guesses']); // unique found letters
if($secret_letters===$found_letters){
// player2 guessed all of the secret letters, set off fireworks
}else{
// some useful bits of code...
$not_yet_found=array_diff($secret_letters,$_SESSION['guesses']);
$underscored=str_replace($not_yet_found,'_',$_SESSION['word']); // e.g. 'ca_'
$space_out=implode(' ',str_split($underscored)); // e.g. 'c a _'
$wrong_letters=array_diff($_SESSION['guesses'],$secret_letters); // letters guessed but not part of secret word
// when count($wrong_letters) reaches your designated limit, then the guesser loses
$avaliable_letters=array_diff(range('a','z'),$_SESSION['guesses']);
$select="<select name=\"guess\"><option>".implode('</option><option>',$available_letters)."</option></select>";
}
I should also note, there are many ways to tackle this project. You should have a look at count_chars(), it has multiple modes which you should research and consider.
There will be regex methods that may be helpful, but I won't open up that can for you.
I see your problem now. you didn't save or hold the previous guess because your found[] array variable is always empty.
try to save the found result in a session
and change this following line of code:
for ($i = 0; $i < strlen($word); $i++) {
if ($counter < strlen($word)) {
if (strpos($word[$i], $guess) !== false) {
$found[] = $guess;
$counter++;
} else {
$found[] = " _ ";
}
}
}
TO:
$counterWord = strlen($word);
for ($i = 0; $i < $counterWord ; $i++) {
if (strpos($word[$i], $guess) !== false) {
$found[$i] = $guess; // $i indicates what index should be changed
} else {
if(!isset($found[$i])){
$found[$i] = "_";
}
}
$_SESSION['found'] = $found;
and add this line of code under the declaring of your $found array variable:
$found = [];
if(isset($_SESSION['found'])){ //checker if the variable is set and not empty
$found = $_SESSION['found']; // getting the value of found and store it in found variable
}

Print to a file a sorted string with numbers and letters, looking for a preg_match solution

Ok, so I have a text file filled with student numbers and the corresponding name. I want to get all those data, format them properly (uppercase, proper number of spaces, etc.) and put them in another file. The original text format is somewhat like this:
20111101613 XXXXXXXX , XXXX
20111121235 xxXXXX, xxxxxx
20111134234 XXXX, XxxX
20111104142 XXXXXxxxX, XXXX
20111131231 XX , XXXXXX
Example:
Input file content is something like this:
20111112346 Zoomba, Samthing
20111122953 Acosta, Arbyn
20110111241 Smith, John
20111412445 Over, Flow Stack
20111112345 foo, BAR
And the output file content should be like this:
20111122953 ACOSTA, ARBYN
20111112345 FOO, BAR
20111412445 OVER, FLOW STACK
20110111241 SMITH, JOHN
20111112346 ZOOMBA, SAMTHING
EDIT: Can someone give me a hint or the solution on how to make this function with using regular expressions?
function sortslist($infile, $outfile)
{
// open the input file named conversion.txt
$inptr = fopen($infile, "r");
if (!$inptr)
{
trigger_error("File cannot be opened: $infile", E_USER_ERROR);
}
// initialize student number to zero
$snum = 0;
// number of letters in the name string
$n = 0;
// initialize the name string to be empty
$name = "";
// iteratively scan the input file
$done = false;
while (!$done)
{
// get each character in the file
$c = fgetc($inptr);
// if the character is a digit, add it to the student number
if (ctype_digit($c))
{
$snum = (($snum * 10) + ($c - '0'));
}
// else, add to name string including commas and space. Input file might have tabs
else if (ctype_alpha($c) || ($n > 0 && ($c == " " || $c == "\t")) || $c == ",")
{
// append the new character to name string
$name .= $c;
// add a space after the comma
if ($c == ",")
{
$name .= " ";
$n++;
}
// increment the number of letters
$n++;
}
// end of the line
else if ($c == "\n" || !$c)
{
// 0 is added to student numbers when newline is detected so neglect them
if ($snum != 0 && $name != "\n")
{
// replace consecutive spaces with one space only
$name = preg_replace(['/\s\s+/', '/\s,/', '/(\s*)(?>$)/'], [' ', ',', ''], $name);
// record student number and name
$info['snum'][] = $snum;
$info['name'][] = strtoupper($name);
}
// reset the values needed
$snum = 0;
$n = 0;
$name = "";
// if we hit the end of the file then it is done
if (!$c)
{
$done = true;
}
}
}
// sort the students names alphabetically
array_multisort($info['name'], $info['snum']);
// combine the name strings and there corresponding student number
$i = 0;
$students = [];
$last_student = end($info['snum']);
foreach ($info['snum'] as $snum)
{
$students[$snum] = $snum . " " . $info['name'][$i++];
// update input file too
fwrite($inptr, $students[$snum]);
// don't add a newline to the end of the file
if ($snum != $last_student)
{
$students[$snum] .= "\n";
}
}
// put it into a new file called slist.txt
file_put_contents($outfile, $students, LOCK_EX);
// close the input file
fclose($inptr);
}
Your problem lies in the fact that $hashtable values are stored with the student ID first in the string. asort() will allways look at the beginning of the value, and sort according to that. So in order to sort by the name, you will have to split up the student ID and the name into two separate arrays and then sort them using array_multisort().
Replace:
$hashtable[$snum] = $snum . " " . strtoupper($name) . "\n";
with:
$snums[] = $snum;
$names[] = strtoupper($name);
array_multisort($names, $snums);
$j = 0;
while ($names) {
$hashtable[$snum] = $snums[$j]. " ". $names[$j]. "\n";
$j++;
}

PHP filter bad words

I have a filter bad words codes below
I want to replace this ARRAY with the .txt file so that I can put all the bad words into the txt file or is there any way to use MYSQL database to store the badwords and then call from there ?
FUNCTION BadWordFilter(&$text, $replace){
$bads = ARRAY (
ARRAY("butt","b***"),
ARRAY("poop","p***"),
ARRAY("crap","c***")
);
IF($replace==1) { //we are replacing
$remember = $text;
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
$text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
}
IF($remember!=$text) RETURN 1; //if there are any changes, return 1
} ELSE { //we are just checking
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
}
}
}
$qtitle = BadWordFilter($wordsToFilter,1);
I just developed a function that can filter out the bad words
function hate_bad($str)
{
$bad = array("shit","ass");
$piece = explode(" ",$str);
for($i=0; $i < sizeof($bad); $i++)
{
for($j=0; $j < sizeof($piece); $j++)
{
if($bad[$i] == $piece[$j])
{
$piece[$j] = " ***** ";
}
}
}
return $piece;
}
and call it like this
$str = $_REQUEST['bad']; //'bad' is the name of the text field here
$good = hate_bad($str);
if(isset($_REQUEST['filter'])) //'filter' is the name of button
{
for($i=0; $i < sizeof($good); $i++)
{
echo $good[$i];
}
}
Yes make a file like bad_words.txt with entries like (note each word combo is on a separate line):
butt,b***
poop,p***
crap,c***
Then read that file into an array like so:
$file_array = file('/path/to/bad_word.txt',FILE_IGNORE_NEW_LINES);
Then to create an array like your $bads array do this:
$bads = array();
foreach ($file_array as $word_combo) {
$bads[] = explode(',', $word_combo);
}
Hope this helps.
You can do either...
You can use something like file_get_contents() to read in from a file, or use a MySQL API to query your database for bad words.
Do you have a database schema set up? Also, eregi_replace() is deprecated. Use preg_replace() instead.
You could use MYSQL.
Just have a table with two columns: the word and the replacement.
Then in your code, you will need to connect to the database and read in each row. But you can then store each row in an array.
The result would be very similar to your current array structure.
To connect to a database, use the tutorial below.
http://www.homeandlearn.co.uk/php/php13p1.html

Mysql/PHP Querying a table value containing reserved words

I'm doing some maintenance on a clients website that uses the simple mysql_query() function for all of their database queries. On one of their pages, a query is done to pull user information based on their nickname. The file is very robust and going through and changing every instance to pull from user IDs instead of nicknames is not really feasible.
They're running into problems with some nicknames, particularly "Link", "Echo", "Slayer". I see why link and echo could potentially cause issues with the query, but not so much Slayer. Is there anything I can do (aside from preventing creation of these names in the future) to help the query go through and pull the information I need?
Edit:
The whole function:
function userInfo($username){
global $username_array;
$username = prepare($username);
$username_array = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `name` = '$username' LIMIT 1"));
}
It should return an array $username_array back to the original script. With 99% of users, this works fine. For some reason, the users above, this done not work.
function prepare($val,$type=0){
$val = XSS($val);
$val = sqlInjection($val);
return $val;
}
function XSS($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
$val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!##$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// &#x0040 # search for the hex values
$val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
// &#00064 # 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'blink', 'script', 'iframe', 'frameset', 'ilayer', 'bgsound');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
$pattern .= '|(&#0{0,8}([9][10][13]);?)?';
$pattern .= ')?';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
function sqlInjection($val){
if (get_magic_quotes_gpc()){
$val = stripslashes($val);
}
if(version_compare(phpversion(),"4.3.0") == "-1"){
return mysql_escape_string($val);
}else{
return mysql_real_escape_string($val);
}
}
There should be no problem since no user input should ever be directly executed.
Make sure you escape the strings properly and consider using prepared statements incase someone has a nasty suprise waiting such as this.
Using strings that are php reserved words is not the issue with your problem.
you can have strings that are reserved words $test = 'function'; is valid. The issue lies elsewhere.
http://www.php.net/manual/en/reserved.keywords.php

what's the code meaning?

$file = fopen("test.txt","r");
while($line = fgets($file)) {
$line = trim($line);
list($model,$price) = preg_split('/\s+/',$line);
if(empty($price)) {
$price = 0;
}
$sql = "UPDATE products
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
fclose($file);
the txt file like this:
model price
LB2117 19.49
LB2381 25.99
1, what's the meaning of list($model,$price) = preg_split('/\s+/',$line);
i know preg_split like explode, but i don't know what't the parameter meaning of the above line
2, how to skip the first record.
it's taking the results of the preg_split and assigning them to the vars $model and $price. You're looking at a parsing algorithm. Sorry if this is not enough. I have a hard time understanding the question as it is written.
Also, if I read this correctly, there is no need to skip line 1 unless you have an item with the model defined as "model" in the database.
But if you wanted to for some reason, you could add a counter...
$i = 0;
while($line = fgets($file)) {
if($i > 0)
{
$line = trim($line);
list($model,$price) = preg_split('/\s+/',$line);
if(empty($price)) {
$price = 0;
}
$sql = "UPDATE products
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
$i++;
}
That is a language construct that allows you to assign to multiple variables at once. You can think of it as array unpacking (preg_split returns an array). So, when you do:
<?php
list($a, $b) = explode(".","a.b");
echo $a . "\n";
echo $b . "\n";
You will get:
a
b
Having less elements in list than the array is ok, excess elements in array are ignored, but having insufficent elements in array will give you an undefined index error. For example:
list($a) = explode(".","a.b"); // ok
list($a,$b,$c) = explode(".","a.b") // error
I don't know if you meant that by skip the first record but...
$file = fopen("test.txt","r"); // open file for reading
$first = true;
while($line = fgets($file)) { // get the content file
if ($first === true) { $first = false;}//skip the first record
else{
$line = trim($line); // remove the whitespace before and after the test
// not in the middle
list($model,$price) = preg_split('/\s+/',$line); // create two variable model and price, the values are from the preg_split \s means whitespace, tab and linebreak
if(empty($price)) { // if $price is empty price =0
$price = 0;
}
$sql = "UPDATE products // sql update
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
}
fclose($file); //close the file

Categories