【问题标题】:PHP strpos not getting the expected resultsPHP strpos没有得到预期的结果
【发布时间】:2014-07-04 12:15:47
【问题描述】:

使用 strpos(),我没有得到我想要的结果。我怀疑问题出在条件语句中。如果条件为真,那么看起来一切正常。但如果它为假,则条件为真的代码仍会执行。这是代码。

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

【问题讨论】:

  • if ($strPosition !== false) 应该是条件。

标签: php strpos


【解决方案1】:

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

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

与,

if ($strPosition !== false) {

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

【讨论】:

  • 老实说,我仍然没有完全理解 !== 但我听从了您的建议。不幸的是,问题仍然存在。即使答案是错误的,显示“未找到”消息的指令仍然没有显示。
  • var_dump($strPosition); 并告诉我们它正在显示什么。
  • 复制,var_dump() = boolean false。
  • 你说如果改变我在回答中提供给你的条件后它仍然会进入?
  • 问题是改成!==后,我并没有为真实条件更改代码块。您的链接实际上很有帮助。现在我想我正在了解 == 和 === 之间的区别,我只需要调整我的代码中的一些语句,我相信我最终会得到我想要的。
【解决方案2】:

来自 php 手册:

返回针存在的位置相对于 haystack > 字符串的开始位置(与偏移量无关)。另请注意,字符串位置从 0 开始,而不是 1。 如果未找到针头,则返回 FALSE。

如果条件改变这个

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

到

if ($strPosition !== false) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多