duan02143 2014-07-04 12:15
浏览 13
已采纳

PHP strpos没有得到预期的结果

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>
  • 写回答

2条回答 默认 最新

  • dongshu9458 2014-07-04 12:21
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?