check white space of a string at the begin [duplicate] - php

This question already has answers here:
Check for whitespace at beginning of string
(4 answers)
Closed 8 years ago.
Is there any way to check the white space at the begin of a string ? I have tried strpos but look like it doesn't work. I use $_POST['text']=" hi" and it output ok in my code. It suppose to be an error.
<form action="#" method="POST">
text <input type='text' name='text'/><br/>
<input type='submit' value='submit'/>
</form>
<?php
if(isset($_POST['text']) && !empty($_POST['text']))
{
if(strpos($_POST['text'],' '))
{
echo 'found white space';
}
else
{
echo 'not found';
}
}
else
{
echo 'none';
}

strpos() will search through the whole string. At the end and in the middle.
Also, you should always use !== false resp. === false when using with strpos().
You can use this for your problem:
if (ctype_space($_POST['text'][0])) {
}
ctype_space() is better than $_POST['text'][0] == ' ', since it also checks for tabs or null characters etc.
PS: If you simply want to remove whitespaces, use trim() . If you just want to remove at the left, you can use ltrim() .

With strpos you find all spaces in your string (or better, first space in your string, not directly first character). Use substr for testing first character.
if (!empty($_POST['text'])) {
if (substr($_POST['text'], 0, 1) == ' ') {
echo 'First char is space';
} else {
echo 'First char isn\'t space';
}
} else {
echo 'String is empty.';
}

if(ltrim($str) == $str)
{
echo 'No Space';
}
else
{
echo 'There are space';
}
This code will check if there are space at the begin of a string.

I got the answer for you. The answer is quite simple you have to just use false and true statement to check weather it has space or not. I have edited your answer please check it.
<form action="#" method="POST">
text <input type='text' name='text'/><br/>
<input type='submit' value='submit'/>
</form>
<?php
if(isset($_POST['text']) && !empty($_POST['text']))
{
$sx=strpos($_POST['text'],' ');
if($sx==true)
{
echo 'found white space';
}
else
{
echo 'not found';
}
}
else
{
echo 'none';
}
Tell if it works

Related

else not executing in php

If I leave all the fields blank, the code blow is not showing the else message.
<form action="index.php" method="POST">
<textarea name="input_area" rows="6" cols="20"></textarea><br/><br/>
Search<input type="text" name="find"/><br/><br/>
Replace<input type="text" name="replace" /><br/><br/>
<input type="submit" value="Find and replace"/>
</form>
PHP
if(isset($_POST['input_area'])&&($_POST['find'])&&($_POST['replace']))
{
$text=$_POST['input_area'];
$find=$_POST['find'];
$replace=$_POST['replace'];
if(!empty($text)&&!empty($find)&&!empty($replace))
{
$new_str=str_replace($find,$replace,$text);
echo $new_str;
}
else
{
echo 'FILL ALL THE FIELDS';
}
}
The values will be set in $_POST, but they will be blank. A check like this would work in all situations, even in some cases where someone has modified your html and tried something funny.
<?php
$text = isset($_POST['input_area']) ? $_POST['input_area'] : "";
$find = isset($_POST['find']) ? $_POST['find'] : "";
$replace = isset($_POST['replace']) ? $_POST['find'] : "";
if($text != "" && $find != "" && $replace != ""){
$new_str=str_replace($find,$replace,$text);
echo $new_str;
}else{
echo 'FILL ALL THE FIELDS';
}
?>
This statement is the root of the problem
if(isset($_POST['input_area'])&&($_POST['find'])&&($_POST['replace']))
The correct one is
if(isset($_POST['input_area'])&&isset($_POST['find'])&&isset($_POST['replace']))
Aman has a pretty good answer. You may want to check if a user just entered spaces though. Look up ctype_space($str) for that. You could also adapt strlen for this purpose and trim to knock off whitespaces that may appear at the beginning or end of the input (or all of it)... if you want your code structure to look the same.
if ( strlen(trim($_POST['input_area']))>0 && etc.

Don't want to display all RecursiveDirectoryIterator files to user

I have a form which the user inputs a file name into. It iterates through all the directories successfully looking to match the users search input to the relevant pdf file.
When it finds the match it correctly echos 'it matches' and breaks out of the foreach loop. However, it also correctly states 'not a match' for all the files it finds before it matches the correct file. So I get a long list of 'not a match ' followed by 'it matches'.
If I echo " " instead of 'not a match' it works fine and doesn't display anything but I would like to tell the user only once that what they have inputted does not match. I am sure I have overlooked something basic but any assistance would be greatly appreciated on how to achieve this.
Here is the code I have.
<?php
if (isset($_POST['submit']) && !empty($_POST['target'])) {
$searchInput = $_POST['target'];
$it = new RecursiveDirectoryIterator("/myDirectory/");
foreach(new RecursiveIteratorIterator($it) as $file) {
$path_info = pathinfo($file);
$extension = $path_info['extension'];
if (strcmp("pdf", $extension) == 0) {
$lowerInput = strtolower($searchInput);
if (!empty($path_info)) {
$string = strtolower($path_info['filename']);
if(preg_match("~\b" . $lowerInput. "\b~", $string)) {
echo "it matches <br>";
break;
} else {
if (!preg_match("~\b" . $lowerInput . "\b~", $string)) {
echo "not a match <br>";
}
}
}
}
} //end foreach
} // end if submit pressed
?>
<html>
<head>
</head>
<body>
<h3>Search Files</h3>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
Type the File You Require:<br><br>
<input id="target" type="text" name="target" required >
<br>
<input id="submit" type="submit" name="submit" value="Search" >
</form>
</body>
</html>
I've left out some of your code, just showing the parts that matter. Basically just set a variable and echo it once when the foreach completes.
$msg="Not a match <br>" ;
foreach(new RecursiveIteratorIterator($it) as $file) {
...
if(preg_match("~\b" . $lowerInput. "\b~", $string)) {
$msg = "it matches <br>" ;
break ;
}
// no need for an else clause, "not a match" is default finding
}// end of foreach
echo $msg ;

PHP After submit check if Data input was sent, and if its less than 3 characters give error

How can i check if this form input was sent to this PHP page and if it's longer than 3 characters? If it's less than 3 characters, I want to print an error.
Form
<form action="index.php" method="post" id="formFlow">
<label for="name" >Name:</label>
<input type="text" name="name" id="name" class="border"/>
</form>
PHP
<?php
$var = $_POST["name"];
if (!empty($var) || strlen($var >= 3)) {
echo "Yes, name is sent";
}else{
echo "Error, name short";
}
?>
First of all you can not use OR operator in your condition becuase it will always true either length of string less than 3 or greater than.
You must need to use && operator.
Second you have an issue in strlen() it must need a string not condition.
Example:
if (!empty($var) && strlen($var) >= 3) {
I think this will solve your problem
<?php
$var = isset($_POST["name"]) ? $_POST["name"] : "";
if (!empty($var) && strlen($var) >= 3) {
echo "Yes, name is sent";
} else {
echo "Error, name short";
}
?>

PHP strpos not getting the expected results

Using strpos(), I'm not getting the results I want. I suspect the problem is in the conditional statements. If the condition is true, everything works fine it seems. But if it is false, the code for the condition true still executes. Here's the code.
<?php
// require_once 'functions/functions.php';
?>
<?php
if (isset($_POST['submit'])) {
$string = $_POST['sentence'];
$findString = $_POST['findstring'];
$strPosition = stripos($string, stringToFind($findString));
// if (($strPosition == true) || ($strPosition == 0)) {
if ($strPosition !== true) {
echo 'Found!', '<br><br>';
echo 'In the string ', $string, '.', '<br>';
echo 'And the word you want to find is ';
$readStr = substr($string, $strPosition, strlen($findString));
echo $readStr, '.', '<br>';
if ($strPosition == 0) {
echo 'It is at the beginning of the string.', '<br>';
}
else {
echo 'It is in the ', $strPosition, ' ', 'position.', '<br>';
}
}
else {
echo 'Not found. Try again.', '<br>';
}
}
function stringToFind($findString)
{
return $findString = $findString;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>String Position</title>
</head>
<body>
<h1>Finding a string and then read it</h1><br><br>
<form id="form1" class="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<label for="sentence">Sentence here:
<textarea id="sentence" name="sentence" value="Put a sentence here."></textarea></label>
Enter a string: <input type="text" name="findstring">
<input type="submit" name="submit" value="Go">
</form><br><br>
</body>
</html>
Yes because your condition gets satisfy even if returns false as you have done a loose comparison with 0. Change your below condition
if (($strPosition == true) || ($strPosition == 0)) {
with,
if ($strPosition !== false) {
Helpful: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
from the php manual:
Returns the position of where the needle exists relative to the beginnning of the haystack > string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
change this if condition
if (($strPosition == true) || ($strPosition == 0)) {
to
if ($strPosition !== false) {

Is this a safe practice in php?

I am trying to make an online calculater where people can calculate using form in my site, people can POST in form and result is GET by url string. Is it safe ?
html
<form id="form1">
<input type="text" name="user_price" size=2/>
<?php echo form_dropdown('selling', $rates);?>
<input type="submit" value="submit">
</form>
php
<?php
if((int)$_GET['user_price']){
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
}else if((string)$_GET['user_price'] OR (array)$_GET['user_price']){
echo 'enter number not characters';
}else{
echo '';
}
?>
Yes, that's perfectly safe, it just doesn't make sense. (int)$_GET['user_price'] casts a value to an integer, it does not mean "if value is an integer".
You're looking for:
if (isset($_GET['user_price'], $_GET['selling']) &&
is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
...
} else {
echo 'Please enter numbers';
}
You could make it much more concise
if (is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
} else {
echo 'Something went wrong';
}
Here is how I would code that...
$userPrice = isset($_GET['user_price']) ? $_GET['user_price']) : NULL;
$selling = isset($_GET['selling']) ? $_GET['selling'] : NULL;
if (is_numeric($userPrice) AND is_numeric($selling)) {
echo 'Total '. $userPrice * $selling;
} else {
echo 'enter number not characters';
}
Note that a good habit to get into, if echoing user submitted strings back, to wrap them with htmlspecialchars().
Perfectly safe, but when using GET and POST you should always declare a variable before you do anything with the form data

Categories