PHP - Apply Trim On Whole Array?
Is there a way to apply the function trim() on a whole array, instead of applying it to the individual input fields one by one?
Here's the code: $blurb1_title = array ( $_POST['blurb1_title1'], $_POST['blurb1_title2'], $_POST['blurb1_title3'], $_POST['blurb1_title4'], $_POST['blurb1_title5'] ); $blurb2_title = array ( $_POST['blurb2_title1'], $_POST['blurb2_title2'], $_POST['blurb2_title3'], $_POST['blurb2_title4'], $_POST['blurb2_title5'] ); $blurb3_title = array ( $_POST['blurb3_title1'], $_POST['blurb3_title2'], $_POST['blurb3_title3'], $_POST['blurb3_title4'], $_POST['blurb3_title5'] ); All those $_POST variables are input fields, and I would like to apply trim() to them so the spaces get removed. Is there an efficient way to do it without having to apply it all individually, if yes, what would be the correct syntax? [php] Similar TutorialsHey Is there a way to trim the print_r($array); so its completed and void of white space? It prints like this: Code: [Select] Array ( [0] => Array ( [id] => 10 [f] => data/tiles/image.png ) ) But I want it to be compressed like this: Code: [Select] Array([0]=>Array([id]=>10[f]=>data/tiles/image.png)) This is then to be stored in the database, so any compressed possible is a plus in this situation. Any ideas? Ok, this was driving me nuts. I think I found the cause, but need help fixing it. I have a bunch of answers in a MySQL database in the form of... Miami Heat/heat/miami Orlando Magic / orlando/ magic etc. etc. *Notice how sometimes there are leading or ending spaces (i.e there is a space before "magic" but NOT a space before "miami")... I run this code to bring back the answers data (all acceptable answers) in an array. I then look for the user entered answer ($userinput, which has trim and strtolower run on it) in the array. Using this code below, the answer IS found if $userinput is any of the Miami Heat options, but it is NOT found if it's any of the Orlando Magic options. The only difference is the fact that there are spaces in the Orlando Magic stuff. Apparently, the trim() function is only removing space from the beggining and end of the ENTIRE string. But I need to trim() each item in the array. How can I do this? Seems like it should be easy but can't figure it out. Code: [Select] $sql = "SELECT * FROM answers WHERE quizid = $quizid"; $result = mysql_query($sql, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } else { while ($getanswers = mysql_fetch_array($result)) { $array = explode("/", strtolower(trim($getanswers['answer']))); if (in_array($userinput,$array)) { echo "the answerid = " . $getanswers['answerid'] . "<br>"; } else { echo "the answerid is not found= <br>"; } } } I have a Form with 10 Questions that a User can choose to answer. I am trying to store the "Answers" into an array like this... Code: [Select] <!-- Question 1 --> <label for="question1">1.) Why did you decide to start your own business?</label> <textarea id="question1" name="answerArray[0]" cols="60" rows="8"><?php if (isset($answerArray[0])){echo htmlentities($answerArray[0], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors['question1'])){ echo '<br /><span class="error">' . $errors['question1'] . '</span>'; } ?> <br /> <!-- Question 2 --> <label for="question2">2.) What advice would you share with others on what NOT to do?</label> <textarea id="question2" name="answerArray[1]" cols="60" rows="8"><?php if (isset($answerArray[1])){echo htmlentities($answerArray[1], ENT_QUOTES);} ?></textarea> <?php if (!empty($errors['question2'])){ echo '<span class="error">' . $errors['question2'] . '</span>'; } ?> <br /> The problem is that when I process the Form, this code is causing issues... Code: [Select] if ($_SERVER['REQUEST_METHOD']=='POST'){ // Form was Submitted (Post). // Initialize Errors Array. $errors = array(); // Trim all form data. $trimmed = array_map('trim', $_POST); I get this error... Code: [Select] Notice: Array to string conversion in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/create_thoughts.php on line 58 Call Stack # Time Memory Function Location 1 0.0014 93944 {main}( ) ../create_thoughts.php:0 2 0.0716 102640 array_map ( ) ../create_thoughts.php:58 How can I either fix my code or change things to do what I need? Thanks, Debbie (1) I need to remove the lowest and higest values from an array. I need to actually remove the two lowest and two highest. I suppose the best thing would be to sort the array and then use a function that just drops the first and last values (twice). Is this the best way? Which function would drop the lowest / highest values? (2) I then need to get the remaining first and last (highest and lowest) values. $array[0] would get first, and revesing the order and $array[0] again would get the last. Is this the best way? I have the following code that queries the database for the results of a quiz. The display reports on completed quizzes, showing, line by line, the quiz title, the date of the quiz, an image of a green tick if the quiz result was correct or an image of a red cross for an incorrect result and a fractional result shoratio of correct answers. A student can repeat a quiz numerous times, and therefore his results for a particulat quiz can display several rows with green ticks and red crosses for the same test done at different times with differing results. I want to recode this so that the red crosses for incorrect results will no longer display once a student achieves a green tick result. I've had several goes at this but my results are less than encouraging. Can anyone help? Do I tackle this through an altered query, or should I include conditions in the display of the array? Code: [Select] <?php $query1 = mysql_query("SELECT DISTINCT quizTitle, userId, passState, userScore, totalScore, DATE_FORMAT(userDate,'%b %e, %Y') AS userDate FROM quiz WHERE managerId = '$managerId' AND userId = '$userId' ORDER BY quizTitle, userDate ASC"); while ($row = mysql_fetch_array($query1)) { echo "{$row['quizTitle']} <br />\n"; echo "{$row['userDate']} <br />\n"; if ("{$row['passState']}" == 1) {echo "<img src=' ../../wood/wood_tool_images/tick2.png' /><br />\n";} if ("{$row['passState']}" == 0) {echo "<img src=' ../../wood/wood_tool_images/cross2.png' /><br />\n";} echo "{$row['userScore']}".'/'."{$row['totalScore']} ?> I'm using the following code to attempt to strip white space from my search results: Code: [Select] while($row = mysql_fetch_assoc($rs)) { trim($row['Name']); trim($row['Address']); trim($row['City']); trim($row['State']); trim($row['Zip']); trim($row['Phone']); echo "<td>" . $row['Name'] . "</td>"; echo "<td>" . $row['Address'] . "</td>"; echo "<td>" . $row['City'] . "</td>"; echo "<td>" . $row['State'] . "</td>"; echo "<td>" . $row['Zip'] . "</td>"; echo "<td>" . $row['Phone'] . "</td>"; echo "<td>" . $row['Type'] . "</td>"; Obviously, I'm leaving out a ton of code, but the important part is that it's not stripping the white space. Things like this make me want to pound spikes into my eyes, because there's just no logical way for me to work though this. I'm extremely OCD, and so if code doesn't work the way the documentation states, I freeze. I also tried (as per another tutorial example) setting a second variable trimming it, and using the second variable in the Echo, like so: Code: [Select] $Tname = ($row['Name']); echo "Blah blah blah" . trim($Tname); That didn't work either. It's simply NOT removing the white space, despite the fact that the entire description of what "Trim" does consists of "removes white space." It boggles my mind. Am I supposed to sacrifice a goat first or something? BTW, if I go in and edit the database manually, I can strip out the spaces by hand, and everything works fine. But it seems to me like the Trim command is supposed to exist to make it so that I don't have to do that. The only thing I can guess is that for some reason the contents of the DB aren't being seen as Strings, even though they are, in fact, Strings. I'm able to maniupulate them as Strings everywhere else in the code. Just not here. Does anyone know what I did wrong? Thanks! Kyle ive used trim to get rid of the end of a a string and it takes an extra character off it anyone can help please Code: [Select] $class_name = "League_Model"; echo $model_name = trim($class_name, "_Model"); result: Leagu im want it to return: league Sorry if this has already been solved. Also, I apologize if this is an amateur question... I have a simple form and a script to do some validating of user data, among other tasks. One part of the script is intended to verify a birthday. Code: [Select] $x = $_POST['x']; $x = trim($x); According to the php.net manual, trim() is supposed to remove whitespace before and after a string. My intent by using trim() is to determine if someone tried to skip the birthday field. I have other validation running on the value of $x, but I wanted trim() to remove whitespace. However, the value of x, which in this case is expected to be numeric, such as 12 for a month, ends up being 1. This happens with any 2-digit number that a user might enter into the form field for x. The second number is always removed. Any insight into why trim() removes the second number, 2 in the above example, leaving only a "1" as the value of $x, would be very greatly appreciated. Thanks in advance. Hello, I have been messing around with this and can't seem to figure out what I'm doing wrong. I'm pretty new to php, so it might be something silly. Original code: Code: [Select] $a1=mysql_result($result,$i,"question"); //Question $a2=mysql_result($result,$i,"answer"); //Answer $a3=mysql_result($result,$i,"submission_id"); //submission id $a4=mysql_result($result,$i,"category"); //submission id echo "<a name=\"$a3\"></a><strong>$a1</strong>$a2"; Prints: Question Category What I want is: Question Category I have tried using the trim functions but nothing seems to help: Code: [Select] $a1=mysql_result($result,$i,"question"); //Question $a2=mysql_result($result,$i,"answer"); //Answer $a3=mysql_result($result,$i,"submission_id"); //submission id $a4=mysql_result($result,$i,"category"); //submission id $a1 = rtrim($a1); $a2 = ltrim($a2); echo "<a name=\"$a3\"></a><strong>$a1</strong>$a2"; Ideas? i have a function that trims all post data $trimmed = array_map('trim', $_POST); however because i am subminting a post array like [locations] => Array ( [0] => Oldham [1] => Royton [2] => Delph [3] => Cheadle ) it gives me an error saying An error occurred in script 'C:\xampp\htdocs\admin\create_listing.php' on line 23: trim() expects parameter 1 to be string, array given how can i stop this all other data is posted in a string however the locations one is posted in an array Hello, I am trying to use the php function string substr ( string $string , int $start [, int $length ] ) to remove trailing zero's in the DB from the price displayed on the page. Currently using the code below I get this for output - $27.9500 <?php echo $row['prodprice']; ?> I would like to get this $27.95. So I tried using the string substr ( string $string , int $start [, int $length ] ) like this - <?php echo substr("$row['prodprice']",0,5); ?> but I receive t string errors and such using variations of this. Can someone please explain to me what I am doing wrong and give me some pointers on how to fix this? Thanks Hi
Using: echo $row['columnname'];
How can I strip off data from the above echo? The column always begins with 'Local/' then 3 digits then other unwanted data, lke 'Local/567@context-0000461d;1'.
It would be ideal to just display '567'.
$string = " hel lo "; $string = rtrim($string); $string= ltrim($string); which trims the whitespace from the front and back, but how do i remove the middle space? Thanks Code: [Select] <label for="first_name">* First Name </label> <input type="text" name="first_name" maxlength="64" value=<?php echo formatPhone(clean_input($_POST['first_name']); ?>> I have a form where I want to enter a first name. I want the fields to take only alphabets(no numbers). Also when a user enters something like John Doe separated by multiple white spaces, I want it to separate the two words only by a single space. I am not sure how this is done in php. Hi - wondering if someone can give a little guidance: Why doesn't this trim the whitespace out of the string postzip? trim(strtoupper(((isset($_POST["postzip"]))?$_POST["postzip"]:""))) Thanks Is there a way to trim everything off in front of the last backslash in the string? Code: [Select] $trimFile = $fList[$i]; Example: In this path: \\\\myftp/downloads/tom/work/word_docs\\legal\test.pdf I only want to display test.pdf. Thanks, Jake Hello
I am Importing CSV file using PHP but it imports with blank lines and white spaces
please guide how to recover this
i am attaching both files for reference
awaiting your valuable reply
Attached Files
dayseatchart.php 4.46KB
1 downloads Hi all I need to remove the spaces in an uploaded file. I have tried str_replace and trim etc... but it doesn't work. Here is my code: Code: [Select] move_uploaded_file($_FILES['image']['tmp_name'][$i], WEB_UPLOAD."/images/galleries/g".$gid."/".$_FILES['image']['name'][$i]) or die("Error uploading image "); Thanks Pete Sorry, I tried to understand the regular expressions but can't figure out the following. How do I take this string /direct1/showtable.php and make it showtable.php. In other words strip out the /direct1/ Once I see how this is done I can apply it to other examples. Thanks! |