PHP Doku:: Findet das erste Vorkommen eines Strings, unabhängig von Groß- und Kleinschreibung - function.stripos.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenstripos

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<stripcslashes

stripslashes>>

stripos

(PHP 5)

striposFindet das erste Vorkommen eines Strings, unabhängig von Groß- und Kleinschreibung

Beschreibung

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

Gibt die numerische Position des ersten Vorkommens von needle innerhalb des Strings haystack zurück.

Im Gegensatz zu strpos() ist stripos() unabhängig von Groß- und Kleinschreibung.

Parameter-Liste

haystack

Die Zeichenkette, in der gesucht werden soll.

needle

Beachten Sie, dass needle eine Zeichenkette von einem oder mehreren Zeichen sein kann.

Ist needle kein String, wird der Parameter in einen Integerwert konvertiert, der dem Ordinalwert des Zeichens entspricht.

offset

Der optionale Parameter offset erlaubt Ihnen anzugeben, ab welchem Zeichen in haystack die Suche begonnen werden soll. Die zurückgegebene Position bezieht sich jedoch auf den Anfang von haystack.

Rückgabewerte

Wenn needle nicht gefunden wird, gibt stripos() den boolean-Wert FALSE zurück.

Warnung

Diese Funktion kann sowohl das boolsche FALSE zurückliefern, als auch einen nicht-boolschen Wert, wie zum Beispiel 0 oder "", der von einem einfachen if-Statement als FALSE ausgewertet wird. Weitere Informationen entnehmen Sie bitte dem Abschnitt über die boolschen Typen. Benutzen Sie deshalb den === Operator, um den Rückgabewert dieser Funktion zu überprüfen.

Beispiele

Beispiel #1 stripos()-Beispiele

<?php
$findmich  
'a';
$meinstring1 'xyz';
$meinstring2 'ABC';

$pos1 stripos($meinstring1$findmich);
$pos2 stripos($meinstring2$findmich);

// 'a' ist natürlich nicht in 'xyz' enthalten
if ($pos1 === false) {
    echo 
"Die Zeichenkette '$findmich' kommt nicht im String '$meinstring1' vor.";
}

// Beachten Sie die Verwendung von ===. Ein einfaches == funktioniert nicht wie
// erwartet, da 'a' an Position 0 (also erster!) Stelle steht
if ($pos2 !== false) {
    echo 
"Die Zeichenkette '$findmich' wurde in '$meinstring2' an Position $pos2 gefunden";
}
?>

Anmerkungen

Hinweis: Diese Funktion ist binary safe.

Siehe auch

  • strpos() - Sucht das erste Vorkommen des Suchstrings
  • strrpos() - Findet das letzte Vorkommen eines Zeichens innerhalb einer Zeichenkette
  • strrchr() - Sucht das letzte Vorkommen eines Zeichens in einem String
  • substr() - Gibt einen Teil eines Strings zurück
  • stristr() - Wie strstr, aber unabhängig von Groß- bzw. Kleinschreibung
  • strstr() - Findet das erste Vorkommen eines Strings
  • strripos() - Findet das letzte Vorkommen der gesuchten Zeichenkette in einem String, unabhängig von Groß- und Kleinschreibung
  • str_ireplace() - Groß- und kleinschreibungsunabhängige Version von str_replace


16 BenutzerBeiträge:
- Beiträge aktualisieren...
guanfenglin at gmail dot com
29.09.2010 5:19
Just a friendly hint:

I came across to this scenario, check to see if an URL string contains http, if no then prepend "http" to the URL string

<?php
$url
= (stripos($url,"http")==false) ? "http".$url : $url;
?>

now, this will always add the http:// to the URL string even the URL string already has http

It is because stripos($url,"http") will return false if no http found, and stripos($url, "http") will return 0 if it is found (being at the start of the string) , and (0==false) is a true condition

therefore, to fix this problem, we have to use (===) to compare the value type as well:

<?php
$url
= (stripos($url,"http")===false) ? "http".$url : $url;
?>

James Lin
gireeshda at yahoo dot com
8.06.2010 7:12
function "stripos" not working in php file without .php extension.  Returns error. Seems to be a bug.

To ensure that stripos works in all php version/platforms in files without .php extension, use the following code:

strpos(strtolower($haystack), strtolower($needle), [ $offset = 0 ] )
vgiralt
19.08.2009 11:38
The mail validator example is NON CONFORMANT with SMTP mail RFCs. Valid characters for Internet e-mail address are more than the ones listed here. Implementing such lame validator is a big disservice to the whole Internet.

Those interested can read RFC 5322. In short, the valid characters are different on both sides of the @ sign, so, before applying this fast technique the address should be exploded into the two side strings, and then, use different valid character strings for the local-part and the domain.

A local part can be any alphabetic or digit US-ASCII character plus "!#$%&'*+-/=?^_`{|}~", and then, if it is enclosed in double-quotes ("), it can be any US-ASCII character except double-quote (") and back-slash(\).

The domain can be any printable US-ASCII characters not including "[", "]", or "\".

And then, this could be overridden with the advent of internationalized domains, that can use UTF-8 character sets.

Implementation of the validator is left as an exercise for the reader.
manualregexp
18.05.2009 12:52
Fast email validator using stripos to check for valid characters.

<?php
function validate_email($value) {
  
$chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ".
                
"abcdefghijklmnopqrstuvwxyz0123456789@._";
  
$at=0/* at sign */
  
$dot=0; /* dot after at */
  
$end_pos = strlen($value)-1;

   for (
$i=0;$i<strlen($value);$i++) {
     
$c = $value[$i];
      if (
stripos($chars, $c)===false) return false;
      if (
$c=="@") $at++;
      if (
$at==1 && $c==".") $dot++;
      if (
$at>1) return false;
     
/* Don't start or end with an '@' or a '.'
       * No @'s or .'s next to each other.
       */
     
if (($c=="." || $c=="@") &&
             (
$i==0 || $i==$end_pos || $prev_c=="." || $prev_c=="@"))
              return
false;
     
$prev_c=$c;
   }
   return (
$at==1 && $dot>0);
}
?>
emperorshishire at gmail dot com
25.02.2009 4: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)
   }
*/
?>
Ysangkok
6.03.2008 16:44
@henke:

No. It does NOT make a warning if the needle isn't found. This is false.
henke at henke37 dot cjb dot net
9.12.2007 19:48
This function will raise a warning if the needle was not found. Be sure to use @ to suppress it if you want the strpos like behavior of only returning false.
hpavon at gmail dot com
19.07.2007 9:54
To shane_at_51smith-dot-nl
Fine but not useful if you want to use stripos 3rd param òffset´ for instance to find all occurences of `needle´.
Again rchillet and heavyraptor solution is best though you'd better keep to-lowercase strings outside the function if you're planning to loop through `haystack´ like this:

$lower_haystack = strtolower($haystack);
$lower_needle = strtolower($needle);
$offset = 0;
//... looping over haystack
while ($offset !== false) {
    $offset = strpos($lower_haystack, $lower_needle, $offset);
    //... some funny stuff here
}

Using rchillet-heavyraptor function here would slow down performance. Solution: don't invent any function
shane_at_51smith-dot-nl
3.07.2007 21:46
Yet another stripos for php4 alternative:
<?php
function stripos($haystack, $needle){
    return
strpos($haystack, stristr( $haystack, $needle ));
}
$strTest = "The brown fox jumped over the Fence";
echo
stripos($strTest, 'fence');//30
?>
grf at post dot cz
20.03.2007 13:57
(i'm very sorry for some mistakes in my yesterday's post :'[ )

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
****************************************/
?>
dazzle
16.08.2006 16:20
I recommend using the solution by rchillet for <PHP5

michiels solution is quite slow if you use it for long strings or call it many times.
michiel at mb-it dot nl
10.07.2006 13:03
Since the stripos-function is PHP5-only, the function below could give PHP4-users the same functionallity:

function stripos($string,$word)
{
   $retval = false;
   for($i=0;$i<=strlen($string);$i++)
   {
       if (strtolower(substr($string,$i,strlen($word))) == strtolower($word))
       {
           $retval = true;
       }
   }
   return $retval;
}
rchillet at hotmail dot com
28.04.2006 10:45
improvement the function of heavyraptor with int offset parametre.

if (!function_exists("stripos")) {
  function stripos($str,$needle,$offset=0)
  {
      return strpos(strtolower($str),strtolower($needle),$offset);
  }
}
heavyraptor
21.03.2006 15:59
If you're using PHP < 5, you can use this alternate function, same thing like stripos:

<?php
if (!function_exists("stripos")) {
  function
stripos($str,$needle) {
   return
strpos(strtolower($str),strtolower($needle));
  }
}
?>

Such a logical function but I hope it helps ...
sim
2.10.2004 19:17
Just to be explicit, the position index returned by strpos starts at 0, not 1. e.g. strpos('abc','a') returns 0.
aidan at php dot net
30.05.2004 19:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)