查找字符串中的字母位置并计算字符串长度


find alphabet position in string and count string length

我试图获得给定字符串中字母表的位置,同时计算字符串的全长,并获得字母表在整数(如索引)中的位置

例如,Talha=5长度,查找T=1

 <?php
    if(isset($_POST['sub'])) 
    {
        $n = $_POST['name'];
        $f = $_POST['f']; 
        $s = strlen($n);  
        $res = strpos($f,$n);
    }else{
        echo "error";
    }
 ?>
    <form method="post">
        <input type="text" name="name" placeholder="name" />
        <br>
        <input type="text" name="f" placeholder="find" />
        <input type="submit" name="sub" />
 <?php 
    if(isset($_POST['sub']))
    {
        echo "total words are". $s. "Your word is". $res; 
    }
 ?>
    </form>

strpos的参数有错误的方法;

应该是:

$res=strpos($n,$f)

此外,如果你想让答案对人类有用,你可能想把$res增加一:

$res=strpos($n,$f)+1

由于strpos将第一个字符视为位置零(0)

我看到的唯一错误是您将参数倒过来了。你在干什么。论点如下:

strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

草垛是你想看的地方,针是你想抬头看的地方。所以你必须做:

strpos($n, $f);

你想在$n,$f中搜索。

PHP-Strpos

编辑:此外,strlen不会给你提供单词总数,而是字符数。您必须使用以下内容:PHP-str_word_count

这里的答案是正确的,对于php上的问题,您应该使用strpos

但是,如果您想向用户展示这一点,您可能应该使用javascript或jquery这里有一个关于javascript 的代码

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Search for Name</button>
<p id="demo"></p>
<script>
function myFunction() {
    var name = "saikios.";
    var n = name.indexOf("k");
    document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

你需要这样的东西吗?

<form method="POST" action="">
    Char to search: <input type="text" name="char" /><br />
    Srting: <input type="text" name="name" /><br />
    <input type="submit" name="sub" value="submit" />
</form>
<?php
if (isset($_POST['sub'])) {
    if (strpos($_POST["name"], $_POST["char"]) !== false) {
        $words = explode(" ", trim($_POST["name"]));
        $wordsCnt = count($words);
        echo "total words are " . $wordsCnt."<br/>";
        echo "Name is: " . $_POST["name"]."<br/>";
        echo "Char what you search is " . $_POST["char"]."<br/>";
        echo "I found the first occurance your char at " . strpos($_POST["name"], $_POST["char"]);
    } else {
        echo "I do not found the character in the name!";
    }
}

所以,如果我把a写为char,把Haystack写为name,你会得到:

total words are 1
Name is: Haystack
Char what you search is a
I found the first occurance your char at 1