strpos的正确返回类型是什么?搜索'@'char


What is the correct return type of strpos? Searching for the '@' char

例如,我有一个字符串I am @ the penthouse.

我需要知道如何在php字符串中找到字符"@"和字符的位置。

我尝试了strpos,但它不起作用。

提前感谢您的帮助。

编辑:

我一直在使用这个来获取字符:

$text = "I am @ the penthouse";
$pos = strrpos($text, '@');
if($pos == true)
{
    echo "yes";
}

我会这么做

注意,我使用的是strpos,而不是反向对应的strrpos

if (($pos = strpos('I am @ the penthouse.', '@') !== false) {
  echo "pos found: {$pos}";
}
else {
  echo "no @ found";
}

注意:因为@可以是字符串中的第一个字符,所以strpos可以返回0。考虑以下内容:

// check twitter name for @
if (strpos('@twitter', '@')) { ... }
// resolves to
if (0) {
  // this will never run!
}

因此,当没有找到匹配项时,strpos将显式返回false。下面是正确检查子字符串位置的方法:

// check twitter name for @
if (strpos('@twitter', '@') !== false) {
  // valid twitter name
}

您也可以为此目的使用strpos()函数。像strrpos()一样,它在字符串中搜索子字符串(或至少是字符),但它返回该子字符串的第一个位置,如果未找到子字符串,则返回布尔值(false)。所以代码片段看起来像:

$position = strpos('I am @ the penthouse', '@');
if($position === FALSE) {
    echo 'The @ was not found';
} else {
    echo 'The @ was found at position ' . $position;
}

注意在php中strpos()strrpos()有一些常见的陷阱。

1。检查返回值的类型!

想象下面的例子:

if(!strpos('@stackoverflow', '@')) {
    echo 'the string contains no @';
}

将输出'@'未找到,尽管字符串包含'@'。这是因为PHP的弱数据类型。前面的strpos()调用将返回int(0),因为它是string中的第一个字符。但是,除非您使用'==='操作符强制执行严格的类型检查,否则int(0)将被处理为FALSE。正确的方法是:

if(strpos('@stackoverflow', '@') === FALSE) {
    echo 'the string contains no @';
}

2。使用正确的参数顺序!

strpos的签名是:

strpos($haystack, $needle [, $start]);

不像PHP中的其他str*函数,其中$needle是第一个参数。

记住这一点!div;)

这似乎是为我在PHP 5.4.7工作:

$pos = strpos('I am @ the penthouse', '@');

strpos不工作到底是什么意思?

看,这对我有用,对你也有用

$string = "hello i am @ your home";
 echo strpos($string,"@");

我希望这对你有帮助-

<?php
$string = "I am @ the penthouse";
$desired_char = "@";
// checking whether @ present or not
if(strstr($string, $desired_char)){
   // the position of the character
   $position = strpos('I am @ the penthouse', $desired_char);
   echo $position;
}
else echo $desired_char." Not found!";
?>