stripos

(PHP 5, PHP 7)

stripos查找字符串首次出现的位置(不区分大小写)

说明

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

返回在字符串 haystackneedle 首次出现的数字位置。

strpos() 不同,stripos() 不区分大小写。

参数

haystack

在该字符串中查找。

needle

注意 needle 可以是一个单字符或者多字符的字符串。

如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符顺序值。

offset

可选的 offset 参数,从字符此数量的开始位置进行搜索。 如果是负数,就从字符末尾此数量的字符数开始统计。

返回值

返回 needle 存在于 haystack 字符串开始的位置(独立于偏移量)。同时注意字符串位置起始于 0,而不是 1。

如果未发现 needle 将返回 FALSE

Warning

此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 说明
7.1.0 开始支持负数的 offset

范例

Example #1 stripos() 范例

<?php
$findme    
'a';
$mystring1 'xyz';
$mystring2 'ABC';

$pos1 stripos($mystring1$findme);
$pos2 stripos($mystring2$findme);

// 'a' 当然不在 'xyz' 中
if ($pos1 === false) {
    echo 
"The string '$findme' was not found in the string '$mystring1'";
}

// 注意这里使用的是 ===。简单的 == 不能像我们期望的那样工作,
// 因为 'a' 的位置是 0(第一个字符)。
if ($pos2 !== false) {
    echo 
"We found '$findme' in '$mystring2' at position $pos2";
}
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • mb_stripos() - 大小写不敏感地查找字符串在另一个字符串中首次出现的位置
  • strpos() - 查找字符串首次出现的位置
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
  • stristr() - strstr 函数的忽略大小写版本
  • substr() - 返回字符串的子串
  • str_ireplace() - str_replace 的忽略大小写版本

User Contributed Notes

Ian Macdonald 29-Aug-2015 07:25
Regarding the === note, it might be worth clarifying that the correct tests for a binary found/not found condition are  !==false to detect found, and ===false to detect not found.
spam at kleppinger dot com 04-Mar-2015 11:08
Regarding the function by spam at wikicms dot org

It is very bad practice to use the same function name as an existing php function but have a different output format.  Someone maintaining the code in the future is likely to be very confused by this.  It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool).

Calling it string_found() or something like that would make a lot more sense for long-term use.
spam at wikicms dot org 15-Dec-2013 05:57
If you like using ternary operator, I wrote simple example how to use stripos function.
Also, in my example I add "How to use namespaces" for wide knowledges for newbies.

<?php
namespace My;

//You can be free using core functions in your NameSpaces (My)
function stripos($haystack, $needle) {
   
//To call core function (from global NS) you should add backslash only - \func
   
return (FALSE === \stripos($haystack, $needle)) ? FALSE : TRUE;
}

var_dump(stripos($haystack = 'John knows English language.', $needle = 'john')); //TRUE
var_dump(stripos($haystack = 'Sara knows English language too.', $needle = 'john')); //FALSE
?>
steve at opilo dot net 02-Jul-2013 01:38
A handy function if you need to adjust layout based on whether or not a string contains descending letters:

<?php function containsDescenders($text) {
   
$descenders = array("g","j","p","q","y");
    foreach (
$descenders as $letter) {
        if (
stripos($text,$letter) !== false) {
            return
true;
        }
    }
    return
false;
}
?>
emperorshishire at gmail dot com 25-Feb-2009 04:31
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach(
$needles as $needle) {
       
$found[$needle] = stripos($haystack, $needle, $offset);
    }
    return
$found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>
grf at post dot cz 20-Mar-2007 01:57
this would to work with any language, i hope.
tested on czech (eastern europe) lang.

<?php
/****************************************
*    SAFE HIGHLIGHT
****************************************/
/**
 * function finds and encase every string in a $needleArr array with
 * strings $shearLft (from the left side) and $shearRgt (guess from which
 * side).
 * already encased needles are IGNORED for any other step, so order
 * of needles in $needleArr is pretty important.
 *
 * function is searching needles in case-insensitive mode,
 * but case in the subject is saved.
 *
 * can you do it better? so, do it.
 *
 * @param array $needleArr array of needles
 * @param string $shearLft left shear
 * @param string $shearRgt right shear
 * @param string $subject subject
 * @param string $encoding encoding ('utf-8' is default)
 *
 * @author griffin
 */
function safeHighlight( $needleArr, $shearLft, $shearRgt, $subject, $encoding = 'utf-8')
{
   
   
// encoding
   
$e = $encoding;
   
   
// oh, no needles
   
if( !is_array( $needleArr))
        return
$subject;
       
   
// empty keys throw-off, only unique, reindex
   
$nA = array_values(
           
array_unique(
               
array_diff( $needleArr, array(''))
            )
        );
   
   
// needle count
   
if( !($nC = count( $nA)))
        return
$subject; // nothing to hl
       
    // shear length
   
if( !(($rLL = mb_strlen( $rL = $shearLft, $e))
    + (
$rRL = mb_strlen( $rR = $shearRgt, $e))))
        return
$subject; // no shears
   
    // subject length
   
if( !($sL = mb_strlen( $s = $subject, $e)))
        return
null; // empty subject
       
    // subject in lowercase (we need to aviod
    // using mb_stripos due to PHP version)
   
$sW = mb_strtolower( $s, $e);
   
   
// masking ~ 0=not changed, 1=changed
   
$m = str_repeat( '0', $sL);
   
   
// loop for each needle
   
for( $n=0; $n<$nC; $n++)
    {
       
       
// needle string loWercase
       
$nW = mb_strtolower( $nA[ $n], $e);
       
       
$o = 0; // offset
       
$nL = mb_strlen( $nW, $e); // needle length

        // search needle
       
while( false !== ($p = mb_strpos( $sW, $nW, $o, $e)))
        {
           
// oh hurrey, needle found on $p position
           
            // is founded needle already modified? (in full-length)
           
for( $q=$p; $q<($p+$nL); $q++)
                if(
$m[ $q])
                {
                   
// ai, caramba. already modified, jump over
                   
$o+= $nL;
                   
                   
// continue for while() loop - not for for() loop!
                   
continue 2;
                }
           
           
// explode subject and mask into three parts
            // partA|needle|partB
           
$sE[0] = mb_substr( $s, 0, $p, $e);
           
$sE[1] = mb_substr( $s, $p, $nL, $e);
           
$sE[2] = mb_substr( $s, $p+$nL, $sL-$p-$nL, $e);
           
           
// mask
            // partA|partB (needle not needed)
           
$mE[0] = mb_substr( $m, 0, $p, $e);
           
$mE[1] = mb_substr( $m, $p+$nL, $sL-$p-$nL, $e);
           
           
// apply shears
           
$sE[1] = $rL.$sE[1].$rR;
           
           
// update sunject length
           
$sL+= $rLL + $rRL;
           
           
// update mask
           
$m = $mE[0] . str_repeat( '1', $rLL + $nL + $rRL) . $mE[1];
           
           
// implode into a subject
           
$s = implode( $sE);
           
           
// update lowercase subject
           
$sW = mb_strtolower( $s, $e);
           
           
// increase offset
           
$o+= $rLL + $nL + $rRL;
           
           
// end of string reached
           
if( $o>=$sL)
                break;
           
        }
// while()
       
   
} // for( $n=0; $n<$nC; $n++)
   
    // oouu yeaaa, kick the subject out of the function
   
return $s;
   
}
// function safeHighlight()
/****************************************
*    END: SAFE HIGHLIGHT
****************************************/
?>