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