PHP strpos没有得到预期的结果

时间:2014-07-04 12:15:48

标签: php strpos

使用strpos(),我没有得到我想要的结果。我怀疑问题出在条件语句中。如果条件为真,那么一切似乎都很好。但如果它为false,则条件true的代码仍然执行。这是代码。

<?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>

2 个答案:

答案 0 :(得分:2)

是的,因为你的条件得到满足,即使你因为与0进行了松散的比较而返回false。更改以下条件

if (($strPosition == true) || ($strPosition == 0)) {

用,

if ($strPosition !== false) {

有帮助: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

答案 1 :(得分:2)

来自php手册:

  

返回针相对于干草堆开始的存在位置&gt;字符串(独立于偏移量)。另请注意,字符串位置从0开始,而不是1。   如果未找到针,则返回FALSE。

如果条件

,则更改此项
if (($strPosition == true) || ($strPosition == 0)) {

if ($strPosition !== false) {