PHP strpos not getting the expected results - php

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) {

Related

Why I get an error with GET before I entered values?

This is my first question here and I'm hardcore newbie in PHP, so don't be to harsh with me :D
I don't understand, why my code printing me an error without me even touched the form. How I can make this code print error only after submitting some values through form?
<?php
$error = "";
if (isset($_GET['a'])) {
$a = htmlentities($_GET['a']);
}
if (isset($_GET['b'])) {
$b = htmlentities($_GET['b']);
}
if (empty($a)) {
$error = "<b>Error:</b> You didn't enter 'a' or 'a' isn't a number<br>";
}
if (empty($b)) {
$error .= "<b>Error:</b> You didn't enter 'b' or 'b' isn't a number<br>";
}
if ($a > $b) {
$error = "<b>Error:</b>Number 'a' can't be bigger than 'b'<br>";
} else {
$sum = (int)$a + (int)$b;
}
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Count sum of two number</title>
</head>
<body>
<h1>Count sum</h1>
<br>
<form action="4.php" method="GET">
Enter a: <input type="text" name="a"><br><br>
Enter b: <input type="text" name="b"><br>
<input type="submit" value="Count">
</form>
<br>
<b>Results:</b>
<?php
if (empty($error)) {
echo $sum;}
else {
echo $error;
}
?>
</body>
</html>
I expect that echo $error will appear only after I submit values in the form, but at this moment I get it printed from the start.
You need to check the variables $a and $b are set before you compare. On the first load, $_GET would be empty and your variables $a and $b won't exist.
So you need to check that the variables exist before the condition check
if (isset($a) && isset($b) && ($a > $b)) {
$error = "<b>Error:</b>Number 'a' can't be bigger than 'b'<br>";
} else {
$sum = (int)$a + (int)$b;
}
PS: You can rearrange the isset($a) && isset($b) condition as per your code requirement. This example is just to show how to use it.

PHP variable is empty in second iteration of loop

Why is the PHP variable defined as $real in the code below empty but still set after one iteration of the while loop yet the $entry variable is both set and contains the correct value on every iteration of the loop. Does the calling of a function '' put the resulting variable outside of the scope and if so how can I fix this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Total </title>
<link type="text/css" rel="stylesheet" href="course.css">
<script src="../jquery.js"></script>
<script src="../jquery-ui.js"></script>
</head>
<body>
<?php
if ($handle = opendir('../uploads'))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
$real= realpath($entry);
echo "<button class='files accordian'>$entry $real</button>";
$real= realpath($entry);
if(isset($real))
{
echo 'the real varibale is set';
}
else
{
echo 'the real varibale is not set';
}
if(empty($real))
{
echo 'the real varibale is empty';
}
else
{
echo 'the real varibale is not empty';
echo 'and is '. $real;
}
echo "<button class='files accordian'>$entry $real</button>
<div class='panel'>
<p>$real</p>";
}
}
}
?>
</body>
</html>
Please change your code where you are getting realpath like below,
$real= realpath("../uploads/".$entry);
Issue: you are just trying to get the realpath of a file. So, it is looking the file in your current path where you are executing your file. Hence, you need to append the origin too.

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 ;

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

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

php - variable from a form - lack of special characters

I'm aware there are many similar questions on this forum, but it's the 2nd day that I'm going through the answers and nothing seems to work.
It's my first week of PHP learning, so please try to answer in a simple way :) So:
I'm creating a conjugator and so far it's going well, but only if I don't use special characters. As Polish verbs are all about special characters, I'm stuck.
This code works (the conjugation is visible on the screen after pressing "submit"):
Page 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Conjugator</title>
</head>
<body>
<form action="new.php" accept-charset="UTF-8" method="post" >
Conjugate: <input type="text" name="verb"><br>
<input type="submit">
</form>
</body>
</html>
Page 2:
<?php
header('Content-Type: text/html; charset="UTF-8"');
$verb = $_POST['verb'];
$last2 = substr ($verb, -2);
$last3 = substr($verb, -3);
$last4 = substr($verb, -4);
$root2 = str_replace($last2, "", $verb);
$root3 = str_replace($last3, "", $verb);
$root4 = str_replace($last4, "", $verb);
$nic = array("nie", "nisz", "ni", "nimy", "nicie", "nia" );
$gnic = array("gnije", "gnijesz", "gnije", "gnijemy", "gnijecie", "gnija");
$ac = array("am", "asz", "a", "amy", "acie", "aja");
if ($last3 == "nic" && $last4 != "gnic") {
foreach ($nic as $one) {
echo "<li>$root3$one</li>";
}
}
elseif ($last4 == "gnic") {
foreach ($gnic as $one) {
echo "<li>$root4$one</li>";
}
}
elseif ($last2 == "ac") {
foreach ($ac as $one) {
echo "<li>$root2$one</li>";
}
}
?>
But if I write for example:
$nic = array("nię", "nisz", "ni", "nimy", "nicie", "nią" );
and then:
if ($last3 == "nić" && $last4 != "gnic")
no result shows up.
For checking, try with verbs like "pienić" or "lśnić" (they don't work) or write them without the special characters ("pienic", "lsnic") - the first code will work.
Help will be deeply appreciated!!
You probably can't use substr() with UTF-8. It thinks in terms of bytes, not characters. Take a look at mb_substr().

Categories