SSISO Community

시소당

문자열관련함수 - strpos

strpos
(PHP  3,  PHP  4  ,  PHP  5)

strpos  --    문자열이  처음  나타나는  위치를  찾습니다.  
설명
int  strpos  (  string  haystack,  string  needle  [,  int  offset])


haystack  문자열에서  needle이  처음  나타나는  수  위치를  반환합니다.  strrpos()와는  달리,  이  함수는  needle  인자로  완전한  문자열을  받아서  전체  문자열을  사용합니다.  

needle을  발견하지  못하면,  strpos()는  boolean  FALSE를  반환합니다.  


주의  
이  함수는  Boolean  FALSE를  반환하지만,  0이나  ""와  같은  FALSE로  취급하는  Boolean이  아닌  값을  반환할  수도  있습니다.  Booleans  섹션에서  자세한  정보를  얻을  수  있습니다.  이  함수의  반환값을  테스트하기  위해서  ===  연산자를  이용하십시오.
  

예  1.  strpos()  예제

<?php
$mystring  =  'abc';
$findme    =  'a';
$pos  =  strpos($mystring,  $findme);

//  ===를  사용하는  점에  주의하십시오.  ==는  'a'가  0번째
//  (처음)  문자이기에  기대하는  대로  작동하지  않습니다.
if  ($pos  ===  false)  {
      echo  "'$findme'  문자열을  '$mystring'  문자열에서  찾지  못했습니다.";
}  else  {
      echo  "'$findme'  문자열을  '$mystring'  문자열에서  찾았습니다.";
      echo  "위치  $pos에  존재합니다.";
}

//  offset  전의  모든걸  무시하고  문자를  찾을  수  있습니다.
$newstring  =  'abcdef  abcdef';
$pos  =  strpos($newstring,  'a',  1);  //  $pos  =  7,  not  0
?>    
  


needle이  문자열이  아니라면,  정수로  변환하여  해당하는  값의  문자를  적용합니다.  

선택적인  offset  인자로  haystack에서  검색을  시작할  문자  위치를  지정할  수  있습니다.  반환하는  위치는  여전히  haystack의  시작  위치로부터  세어집니다.  

참고:  strrpos(),  stripos(),  strripos(),  strrchr(),  substr(),  stristr(),  strstr().  




  add  a  note  User  Contributed  Notes
strpos  
Ed  Lecky-Thompson
27-Apr-2005  01:02  
Here's  a  quick  function  which  can  replace  strtotime,  and  will  work  fine  on  dates  pre-1970  (i.e.  it  will  return  a  negative  number  as  expected).

This  negative  time  stamp  seems  to  be  supported  as  an  input  parameter  by  methods  like  date()  up  to  a  point,  but  if  you  get  crazy  and  start  talking  about  dates  in  the  1700s  (everybody  was  using  PHP3  back  then,  of  course)  it  gets  upset.

For  those  of  you  doing  staff  databases  and  so  forth,  of  course,  this  is  probably  fine  -  it's  definitely  OK  for  any  dates  post  1900,  and  this  value  has  been  hard  coded  into  the  function  below.

      function  safestrtotime($strInput)  {
              $iVal  =  -1;
              for  ($i=1900;  $i<=1969;  $i++)  {
                      #  Check  for  this  year  string  in  date
                      $strYear  =  (string)$i;
                      if  (!(strpos($strInput,  $strYear)===false))  {
                              $replYear  =  $strYear;
                              $yearSkew  =  1970  -  $i;
                              $strInput  =  str_replace($strYear,  "1970",  $strInput);
                      };
              };
              $iVal  =  strtotime($strInput);
              if  ($yearSkew  >  0)  {
                      $numSecs  =  (60  *  60  *  24  *  365  *  $yearSkew);
                      $iVal  =  $iVal  -  $numSecs;
                      $numLeapYears  =  0;                #  Work  out  number  of  leap  years  in  period
                      for  ($j=$replYear;  $j<=1969;  $j++)  {
                              $thisYear  =  $j;
                              $isLeapYear  =  false;
                              #  Is  div  by  4?
                              if  (($thisYear  %  4)  ==  0)  {
                                      $isLeapYear  =  true;
                              };
                              #  Is  div  by  100?
                              if  (($thisYear  %  100)  ==  0)  {
                                      $isLeapYear  =  false;
                              };
                              #  Is  div  by  1000?
                              if  (($thisYear  %  1000)  ==  0)  {
                                      $isLeapYear  =  true;
                              };
                              if  ($isLeapYear  ==  true)  {
                                      $numLeapYears++;
                              };
                      };
                      $iVal  =  $iVal  -  (60  *  60  *  24  *  $numLeapYears);
              };
              return($iVal);
      };  
yess  at  eleethal  dot  com
25-Apr-2005  12:18  
Regarding  James  Perlman's  findStr(),  it's  very  nice  although  doesnt  always  return  true  when  it  should.    I  found  fnmatch()  to  be  a  more  accurate  function  for  'wildcard  matching'.  I'm  building  an  IRCd  and  require  wildmatching  for  many  different  commands.  Hope  this  helps  somone.

<?
findStr("12.12.12.*","12.12.12.12");  //returns  null,  should  return  true

fnmatch("12.12.12.*","12.12.12.12");  //returns  1.
?>  
webKami  [at]  akdomains.com
01-Apr-2005  05:37  
You  can  easily  skip  these  two  meaningless  comment  lines  in  my  last  function.These  comments  are  for  old  version  of  the  function,  I  was  not  using  length  of  needle  in  that  version.  Code  is  fine  itself,  I  suppose  ;)
<?
...

//start  $pos  from  -1,  cause  we  are  adding  1  into  it  while  searchig
//so  the  very  first  iteration  will  be  0

...
?>  
webKami  [at]  akdomains.com
01-Apr-2005  12:06  
Str  Pos  Nth  (Position  of  nth  occurance  of  a  string)
A  handy  function  to  get  the  position  of  nth  occurance  of  a  substring  in  a  string,  with  an  optional  param  to  make  it  case  insenstive.  I  am  calling  it  strposnth,  suggestions  welcome.

Third  optional  parameter  gets  the  value  of  n,  e.g  puting  in  2  will  return  position  of  second  occurance  of  needle  in  haystack:  Valid  inputs  (1  =  default)  2,3,4.....  

Fourth  optional  parameter  can  be  used  to  specify  the  function  as  case  insenstive:  Valid  inputs  (0  =  case  senstive  =  default)  1  =  case  insenstive.

Code:
<?

function  strposnth($haystack,  $needle,  $nth=1,  $insenstive=0)
{
      //if  its  case  insenstive,  convert  strings  into  lower  case
      if  ($insenstive)  {
              $haystack=strtolower($haystack);
              $needle=strtolower($needle);
      }
      //count  number  of  occurances
      $count=substr_count($haystack,$needle);
      
      //first  check  if  the  needle  exists  in  the  haystack,  return  false  if  it  does  not
      //also  check  if  asked  nth  is  within  the  count,  return  false  if  it  doesnt
      if  ($count<1  ||  $nth  >  $count)  return  false;

      
      //run  a  loop  to  nth  number  of  accurance
      //start  $pos  from  -1,  cause  we  are  adding  1  into  it  while  searchig
      //so  the  very  first  iteration  will  be  0
      for($i=0,$pos=0,$len=0;$i<$nth;$i++)
      {        
              //get  the  position  of  needle  in  haystack
              //provide  starting  point  0  for  first  time  ($pos=0,  $len=0)
              //provide  starting  point  as  position  +  length  of  needle  for  next  time
              $pos=strpos($haystack,$needle,$pos+$len);

              //check  the  length  of  needle  to  specify  in  strpos
              //do  this  only  first  time
              if  ($i==0)  $len=strlen($needle);
          }
      
      //return  the  number
      return  $pos;
}

?>

I  just  construct  this  function  after  trying  to  search  a  similar  one  to  use  in  a  shopping  cart.  I  am  using  this  to  display  a  limited  number  of  lines  or  text  for  featured  products.  My  aim  is  to  limit  the  product  description  to  100  characters  or  3  lines  /  3  list  items  whichever  is  less.

Example  code  goes  like  this
<?

//get  the  product  description  from  recordset
$text=$row['product_desc'];

//strip  off  text  if  its  longer  than  100  characters
if  (strlen($text)>100)  $text=substr($text,0,100)."  ...";

//get  ending  of  the  third  line
$pos=strposnth($text,"\n",3,1);

//if  found,  strip  off  text  after  that
if($pos)  $text=substr($text,0,$pos);

//nl2li  (new  line  2  list)  this  function  converts  the  \n  seprated  lines  of  text  into  sorted  or  unsorted  lists
//I  have  posted  this  function  in  nl2br
//http://uk2.php.net/manual/en/function.nl2br.php
$text=nl2li($text);  
echo  $text;

?>

Examples:

strposnth("I  am  trying  to  go  now.","o");  //  returns  13  (strpos  behavior)
strposnth("I  am  trying  to  go  now.","O");  //  returns  false  (strpos  behavior)
strposnth("I  am  trying  to  go  now.","o",2);  //  returns  16  (second  occurance)
strposnth("I  am  trying  to  go  now.","o",7);  //  returns  false  (occurance  count  is  less  than  7)
strposnth("I  am  trying  to  go  now.","O",1,1);  //  returns  13  (stripos  behavior)
strposnth("I  am  trying  to  go  now.","O",3,1);  //  returns  19  (stripos  behavior  +  nth  occurance)

Suggestions  and  corrections  are  welcome.
Regards,

webKami  [at]  akdomains.com  
edykory  at  bluebottle  dot  com
23-Mar-2005  09:49  
a  shorter  version  of  "admin  at  bwongar  dot  com"  searching  function:

function  strpos_array($haystack,  $needle){
    while  (($pos  =  strpos($haystack,  $needle,  $pos))  !==  FALSE)
                                  $array[]  =  $pos++;
    return  $array;
}
  I  like  "arias"  version,  but  I  guess  strlen(aguja)  can  be  cached  in  a  local  variable.  
damy_belthazor86  at  yahoo  dot  it
09-Mar-2005  05:10  
Aw..  I  forgot  to  post  the  usage  of  my  function  :)

Here's  an  example  in  which  an  array  is  filled  of  all  the  values  of  the  attribute  src  of  the  tag  img.
<?php
$imgSrcValues  =  getTagAttributeValues($rteHtml,"<IMG","src=");
?>

bye!  
08-Mar-2005  09:32  
<?

//  You  can  use  this  to  get  the  real  path...

$include_path  =  getenv("PATH_TRANSLATED");

echo  $include_path  =  substr($include_path,  strpos($include_path,  "/"),  strrpos($include_path,  "/"));

?>  
arias  at  elleondeoro  dot  com
07-Feb-2005  11:33  
If  you  want  to  get  all  positions  in  an  array,  you  can  use  this  function.  If  the  optional  parameter  count  is  especified,  the  function  will  put  there  the  number  of  matches.

function  strallpos($pajar,  $aguja,  $offset=0,  &$count=null)  {
    if  ($offset  >  strlen($pajar))  trigger_error("strallpos():  Offset  not  contained  in  string.",  E_USER_WARNING);
    $match  =  array();
    for  ($count=0;  (($pos  =  strpos($pajar,  $aguja,  $offset))  !==  false);  $count++)  {
      $match[]  =  $pos;
      $offset  =  $pos  +  strlen($aguja);
    }
    return  $match;
}  
admin  at  bwongar  dot  com
21-Jan-2005  11:17  
I  created  a  useful  function  that  returns  an  array  with  the  positions  within  a  string.  For  more  info,  read  the  comments:
<?php
//  Returns  an  array  in  this  fashion:
//  array(count  =>  position)
function  strpos_array($haystack,  $needle){
      $kill        =  0;        //  Kills  while  loop  when  changed
      $offset        =  0;        //  Offset  for  strpos()
      $i                =  0;        //  Counter,  not  iterator

      while  ($kill  ===  0)  {
              $i++;
              $result  =  strpos($haystack,  $needle,  $offset);  

              if  ($result  ===  FALSE)  {                //  If  result  is  false  (no  more  instances  found),  kill  the  while  loop
                      $kill  =  1;
              }  else  {
                      $array[$i]  =  $result;        //  Set  array
                      $offset  =  $result  +  1;        //  Offset  is  set  1  character  after  previous  occurence
              }

      }

      return  $array;

}
?>  
Benjamin
10-Jan-2005  03:46  
James  Perlman's  function  is  nice  but  he  should  REALLY  use  a  regular  expression:

http://php.net/manual/en/function.ereg.php  
takapz  at  flor  dot  it
04-Dec-2004  02:28  
here  a  little  function  for  tag  parsing

function  parsing($tag,$string)  {
              $start=strpos($string,"<"  .  $tag  .  ">"  );
              $start=$start  +  strlen("<"  .  $tag  .  ">");
                  $end=(strpos($string,  "</"  .  $tag  .  ">"));
                  $num=    ($end  -  $start);
                  $valore=substr($string,$start,$num);
                  return  $valore;
}  
James  Perlman
11-Nov-2004  05:06  
Here's  a  nifty  function  i  made,  that  allows  you  to  search  a  string  using  wildcards.    It  was  intentionally  made  as  part  of  a  ban  system.

Here  is  the  function:
(below  is  how  to  use  the  function)

<?php
function  findStr($search,  $target)  {
      $matches  =  0;
      $search  =  strtolower($search);
      $target  =  strtolower($target);
      $output  =  "";
      //  Create  the  "search"  array,  which  holds  all  our  search  terms
      $search  =  explode("*",$search);  //  You  could  change  this  to:  '$search  =  explode("  ",$search);'  if  you  wanted  your  search  terms  to  be  split  by  a  space.
      $pos  =  0;
      for  ($i=0;  $i<count($search);  $i++)  {
              //  Check  if  the  current  search  term  is  in  our  target
              if  (strpos($target,  $search[$i],  $pos)  !=  ''  &&  strlen($search[$i])>0)  {
                      $pos  =  strpos($target,  $search[$i],  $pos);
                      $matches++;
              }  
              if  (strlen($search[$i])<1)  {
                      $matches++;
              }
      }
      if  ($matches  ==  count($search))  {
              return  true;
      }  else  {
              return  false;
      }
}
?>

How  to  use  the  function:
<?
echo  findStr("34.12.85.*","34.12.85.98");  //  would  return  true
echo  findStr("3*.12.*.90","39.16.29.34");  //  would  return  false
?>
The  function  searches  to  see  if  all  the  search  terms  are  in  the  string,  and  if  they  are  in  the  exact  order  you  gave  them  in.

Hope  you  found  this  function  to  be  helpful!
-James  
ygrange  at  science  dt  uva  dt  nl
14-Sep-2004  08:15  
Hmm.  I  think  the  maker  of  multi_strpos  forgot  to  add  that  it  allowed  a  negative  position  (if  $n=0,  $position[($n-1)]  =  $position[-1].  I  just  changed  a  slightly  bit  of  the  code  to  make  it  really  correct.  

I  just  replace  
$position[$n]  =  (strlen($fragment[0])  +  $position[($n-1)]);
by
$position[$n]  =  (strlen($fragment[0])  +  $positione[$n]);
$positione[$n+1]=$position[$n];  
philip
26-Aug-2004  07:52  
Many  people  look  for  in_string  which  does  not  exist  in  PHP,  so,  here's  the  most  efficient  form  of  in_string()  (that  works  in  both  PHP  4/5)  that  I  can  think  of:  
<?php  
function  in_string($needle,  $haystack,  $insensitive  =  0)  {  
      if  ($insensitive)  {  
              return  (false  !==  stristr($haystack,  $needle))  ?  true  :  false;  
      }  else  {  
              return  (false  !==  strpos($haystack,  $needle))    ?  true  :  false;  
      }  
}  
?>  
christian  dot  NEI_TIL_SPAM  at  datalogen  dot  no
20-Aug-2004  03:26  
If  you  want  to  find  the  position  of  the  first  character  succeeding  $needle,  this  function  does  it  for  you.  $offset  is  optional.

<?php

function  strpos_succ($haystack,  $needle)  {
      $offset  =  (func_num_args()  >  2)  ?  func_get_arg(2)  :  0;
      $res  =  strpos($haystack,  $needle,  $offset);
      return  (($res  ===  false)  ?  false  :  $res  +  strlen($needle));
}

?>

Example:
<?php
      $str  =  'Mighty  <a  href="nowhere.htm">useful</a>  function,  this  strpos_succ!';
      //Where  does  the  first  <a>  tag  in  $str  end?
      $aPos  =  strpos_succ($str,  ">");
      //  $aPos=29
?>  
php  .at.  wwwcrm  .dot.  com
20-Aug-2004  02:33  
Watch  out  for  type!

The  following  code  will  return  "not  matched",  which  is  a  little  counter-intuitive.

<?php
$val1=123;
$val2="123,456,789";
if  (strpos($val2,  $val1)!==false)  echo  "matched";
else  echo  "not  matched";
?>

When  $val1  is  cast  to  string,  it  behaves  as  you  might  expect:

<?php
$val1=(string)123;
$val2="123,456,789";
if  (strpos($val2,  $val1)!==false)  echo  "matched";
else  echo  "not  matched";
?>

Hope  this  saves  someone  the  couple  of  hours  that  it  took  me  to  spot  it  :-)

Regards,
Alex  Poole  
bishop
22-Apr-2004  07:38  
Code  like  this:
<?php
if  (strpos('this  is  a  test',  'is')  !==  false)  {
      echo  "found  it";
}
?>

gets  repetitive,  is  not  very  self-explanatory,  and  most  people  handle  it  incorrectly  anyway.  Make  your  life  easier:

<?php
function  str_contains($haystack,  $needle,  $ignoreCase  =  false)  {
      if  ($ignoreCase)  {
              $haystack  =  strtolower($haystack);
              $needle    =  strtolower($needle);
      }
      $needlePos  =  strpos($haystack,  $needle);
      return  ($needlePos  ===  false  ?  false  :  ($needlePos+1));
}
?>

Then,  you  may  do:
<?php
//  simplest  use
if  (str_contains('this  is  a  test',  'is'))  {
      echo  "Found  it";
}

//  when  you  need  the  position,  as  well  whether  it's  present
$needlePos  =  str_contains('this  is  a  test',  'is');
if  ($needlePos)  {
      echo  'Found  it  at  position  '  .  ($needlePos-1);
}

//  you  may  also  ignore  case
$needlePos  =  str_contains('this  is  a  test',  'IS',  true);
if  ($needlePos)  {
      echo  'Found  it  at  position  '  .  ($needlePos-1);
}
?>  
amy_w  at  gmx  dot  de
03-Apr-2004  02:41  
You  can  use  this  function  to  find  ANY  occurence  of  a  string  in  an  array  -  no  matter  if  it  is  just  part  of  one  of  the  array  elements.  

it  returns  the  key  of  the  first  found  occurence  or  false  

<?php  
function  search_array($needle,$haystacks)  {  
      $found=false;  
      foreach  ($haystacks  as  $key  =>  $haystack)  {  
              if  (!(strpos($haystack,$needle)===false))  {  
                      $found=$key;  
                      break;  
              }  
      }  
      return  ($found);  
}  
?>  
ebypdx  at  comcast  dot  net
10-Mar-2004  10:26  
counting  the  occurrences  of  a  substring,  recursive-style  instead  of  looping.
<?
function  countSubstrs($haystack,  $needle)
{
      return  (($p  =  strpos($haystack,  $needle))  ===  false)  ?  0  :  (1  +  countSubstrs(substr($haystack,  $p+1),  $needle));
}
?>  
nanobot2k  at  nanobot2k  dot  org
16-Feb-2004  06:45  
This  function  will  return  the  number  of  times  a  needle  is  found  in  a  haystack...if  none  that  it  will  return  0.

Cheers  to  lgbr  for  saving  me  the  headache!  :P
<?php
/**
  *  @return  int
  *  @param  string  $haystack
  *  @param  string  $needle
  *  @desc  returns  the  number  of  times  a  needle  is  found  in  a  haystack,  0  if  none  found
*/
function  totalStr($haystack,  $needle,$i  =  0)
{
      while(strpos($haystack,$needle)  !==  false)  {
              $haystack  =  substr($haystack,  (strpos($haystack,$needle)  +  1));
              $i++;
      }
      return  $i;
}
?>  
kingbusiness  at  hotmail  dot  com
19-Dec-2003  03:34  
A  simple  function  to  find  the  number  of  occurances  in  a  string  within  a  string  

<?php  
function  StringCount($searchstring,  $findstring)  
{  
      return  (strpos($searchstring,  $findstring)  ===  false  ?  0  :    count(split($findstring,  $searchstring))  -  1);  
}  
?>  
jackylee  at  eml  dot  cc
20-Nov-2003  03:17  
enough  to  search  and  replace  a  new  string  into  a  text  file.  
hope  this  can  save  your  time  :-)  

original  config.txt  file:  
Current  Background  =  [wallpaper/WinXP.jpg]  
Last  Time  =  [20]  

<?php  
    $var  =  file_get_contents("data/config.txt");  

    $out  =  fopen("data/config.txt",  "w");  
    $var2  =  writeConfig($var  ,  "Current  Background  =  ["  ,  "]"  ,  "wallpaper/Bgred.jpg");    
    $var2  =  writeConfig($var2,  "Last  Time  =  ["  ,  "]"  ,  "21");    
    fwrite($out,  $var2);  
    fclose($out);    

function  writeConfig($var,  $begString,  $endString,  $newString)  
{  
    $begPos  =  strpos($var,$begString)  +strlen($begString);  
    $endPos  =  strpos($var  ,  $endString  ,  $begPos);  
    $result  =  substr($var,  0,  $begPos);  
    $result  .=  $newString;  
    $result  .=  substr($var,  $endPos);  
    return  $result;  
}  
?>  

changed  config.txt  file:  
Current  Background  =  [wallpaper/Bgred.jpg]  
Last  Time  =  [21]  
peous  at  djingle  dot  com
04-Oct-2003  05:54  
Function  to  find  the  first  occurence  of  any  object  of  the  array.  

<?php  
function  findfirstof(  $txt,  $arr,  $start  )  
{  
      $pos  =  -1;  
      foreach(  $arr  as  $v  )  
      {  
              $p  =  strpos(  $txt,  $v,  $start  );  
              if  ($p===FALSE)  
                      continue;  
              if  (($p<$pos)||($pos==-1))  
                      $pos  =  $p;  
      }  
      return  $pos;  
}  
?>  

Ex:  
$str  =  "find,  the  first  word...";  
$firstW  =  findfirstof(  $str,  ",?.:!"  );  //returns  "find"  
justin  at  visunet  dot  ie
02-Oct-2003  01:20  
Function:  
stripos_words($haystack,'words  in  string')  

This  function  finds  and  reports  positions  of  all  words  in  supplied  haystack.  It  returns  the  results  as  an  array.  The  array  has  the  following  structure.  

Array  
(  
      [69]  =>  Array  
              (  
                      [start]  =>  69  
                      [end]  =>  74  
                      [word]  =>  honey  
              )  

      [226]  =>  Array  
              (  
                      [start]  =>  226  
                      [end]  =>  232  
                      [word]  =>  cobweb  
              )  
}  

Where,  for  convenience,  the  main  key  also  contains  the  positions  of  each  found  word  occurrence.  

If  you  want  the  main  key  to  be  0,1,2,3,etc  then  set  the  third  parameter  ($pos_as_key)  to  false;  

Hope  this  is  of  help  to  someone.  

Cheers,  
Justin  :)  

<?php  
function  stripos_words($haystack,$needles='',$pos_as_key=true)  
{  
      $idx=0;  //  Used  if  pos_as_key  is  false  
      
      //  Convert  full  text  to  lower  case  to  make  this  case  insensitive  
      $haystack  =  strtolower($haystack);  
      
      //  Split  keywords  and  lowercase  them  
      foreach  (  preg_split('/[^\w]/',strtolower($needles))  as  $needle  )  
      {  
              //  Get  all  occurences  of  this  keyword  
              $i=0;  $pos_cur=0;  $pos_found=0;  
              while  (    $pos_found  !==  false  &&  $needles  !==  '')  
              {  
                      //  Get  the  strpos  of  this  keyword  (if  thereis  one)  
                      $pos_found  =  strpos(substr($haystack,$pos_cur),$needle);  
                      if  (  $pos_found  !==  false  )  
                      {  
                              //  Set  up  key  for  main  array  
                              $index  =  $pos_as_key  ?  $pos_found+$pos_cur  :  $idx++;  
                              
                              //  Populate  main  array  with  this  keywords  positional  data  
                              $positions[$index]['start']  =  $pos_found+$pos_cur;  
                              $pos_cur  +=  ($pos_found+strlen($needle));  
                              $positions[$index]['end']    =  $pos_cur;  
                              $positions[$index]['word']  =  $needle;  
                              $i++;  
                      }  
              }  
      }  

      //  If  we  found  anything  then  sort  the  array  and  return  it  
      if  (  isset($positions)  )  
      {  
              ksort($positions);  
              return  $positions;  
      }  

      //  If  nothign  was  found  then  return  false  
      return  false;  
}  
?>  
daijoubu  at  videotron  dot  ca
30-Aug-2003  08:48  
To  previous  comments:
I  did  a  test  with  500000  iterations,  string  lenght  was  1846bytes  long  and  the  word  to  find  was  near  the  end.

Results:
if  (*)
Total  time  in  secs
Average

strpos($test,  'Possibly')  ===  true
5.1114
0.0000102228  

strpos('  '.$test,  'Possibly')  >  1
7.2559
0.0000145117  

is_int(strpos($test,  'Possibly'))
5.5331
0.0000110661  

strstr($test,  'Possibly')
5.1461
0.0000102922

Clearly  shows  that  ===  operator  is  the  fastest  
wodzuY2k  at  interia  dot  pl
07-Apr-2003  07:31  
this  loop  removes  <script>.*</script>  tags  from  HTML  contents.  

<?php  
while(true)  
{  
      $begPos  =  strpos($contents,"<script");  
      if  ($begPos===false)  break;  //all  tags  were  found  &  replaced.  
      $endPos  =  strpos($contents,"script>",$begPos+strlen("<script"));  
      $tmp  =  substr($contents,0,$begPos);  
      $tmp  .=  substr($contents,$endPos+strlen("script>"));  
      $contents  =  $tmp;  
      if  ($loopcontrol++>100)  break;  //loop  infinity  control  
      continue;    //search  again  
};  
?>  
bebop  at  gmx  dot  at
31-Mar-2003  11:02  
just  another  workaround  for  the  true/0  problem:  

<?php  
if  (!is_int(strpos($haystack,$needle)))  {  
      //do  something  
}  
?>  

should  also  do  the  job  
arduenn  at  hotpop  dot  com
18-Jan-2003  09:45  
Hi  all,

This  function  returns  an  array  of  positions  (as  integers)  of  a  regular  expression  pattern  that  could  occur  several  times  within  a  string  (or  FALSE  if  the  pattern  does  not  occur).  Note  that  the  function  is  able  to  determine  the  positions  of  overlapping  patterns.  There  may  be  shorter  ways  of  determining  multiple  pattern  positions  (such  as  by  using  'explode')  but  likely  these  won't  find  the  overlapping  patterns.

The  multi_strpos  function  has  one  restriction  (for  the  sake  of  snippet  economy):  if  you  use  a  pattern  starting  with  '\*'  (backslash  asterisk)  a  hit  within  the  string  will  invoke  an  infinite  loop.

This  function  was  initially  written  to  create  restriction  maps  of  DNA  sequences  but  you  may  find  other  uses.

<?

function  multi_strpos($pattern,  $sequence)  {
    $n  =  -1;
    while  (ereg($pattern,  $sequence))  {
      $n++;
      $fragment  =  split($pattern,  $sequence);
      $trimsize  =  (strlen($fragment[0]))+1;
      $sequence  =  "*".substr($sequence,  $trimsize);
      $position[$n]  =  (strlen($fragment[0])  +  $position[($n-1)]);}
    return  $position;}

//  Below  some  code  to  demonstrate  the  function.

$testsequence  =  "She  sells  sea  shells  at  the  see  shore.";
echo  "Test  sequence  =  '$testsequence'\n\n";

$testpattern  =  "s...s";
echo  "Regular  expression  pattern  =  '$testpattern'\n\n";

$position  =  multi_strpos($testpattern,  $testsequence);

if  ($position)  {
    echo  "Pattern  match  found  at:\n";
    while  (list($index,  $pos)  =  each($position))  {
      echo  "$pos\n";}}

?>  
netmail  at  brownfloyd  dot  com
30-Dec-2002  03:31  
Description:  

array  straipos  (  string  haystack,  array  needle  [,  int  offset])  

Returns  an  indexed  array  of  the  item  from  the  array  'needle'  that  occurs  first  in  the  haystack,  with  item  0  being  its  position  in  the  'haystack',  and  item  1  being  the  item  number  of  the  item  found.  

If  none  of  the  items  are  found,  it  returns  false.  

<?php  
function  straipos($haystack,$array,$offset=0)  
{  
      $occ  =  Array();  
      for  ($i  =  0;$i<sizeof($array);$i++)  
      {  
              $pos  =  strpos($haystack,$array[$i],$offset);  
              if  (is_bool($pos))  continue;  
              $occ[$pos]  =  $i;  
      }  
      if  (sizeof($occ)<1)  return  false;  
      ksort($occ);  
      reset($occ);  
      list($key,$value)  =  each($occ);  
      return  array($key,$value);  
}  
?>  
admin  at  kingdompeople  dot  com
27-Sep-2002  05:19  
the  following  2  functions  grab  a  piece  of  content  from  an  external  html  and  lists  that  in  separate  places  --  i.e.  the  title  for  html  documents,  or  a  list  of  subtopics  dynamically..  the  first  function  grabs  the  first  found  and  returns  a  string,  the  second  recursively  searches  the  rest  of  the  document  and  returns  an  array..  
I  found  this  was  very  useful  to  display  articles  on  my  website  that  had  various  topics  marked  by  a  consistent  <P  class=subtopic>,  and  the  end  </  P>  tags..  

<?php  
function  stripfromtext($haystack,  $bfstarttext,  $endsection)  {  
    $startpostext  =  $bfstarttext;  
    $startposlen  =  strlen($startpostext);  
    $startpos  =  strpos($haystack,  $startpostext);  
    $endpostext  =  $endsection;  
    $endposlen  =  strlen($endpostext);  
    $endpos  =  strpos($haystack,  $endpostext,  $startpos);  
    return  substr($haystack,  $startpos  +  $startposlen,  $endpos  -  ($startpos  +  $startposlen));  
}  

function  &stripfromtextarray($haystack,  $bfstarttext,  $endsection,  $myarray=array(),  $offset=0)  {  
    $startpostext  =  $bfstarttext;  
    $startposlen  =  strlen($startpostext);  
    $startpos  =  strpos($haystack,  $startpostext,  $offset);  
    $endpostext  =  $endsection;  
    $endposlen  =  strlen($endpostext);  
    $endpos  =  strpos($haystack,  $endpostext,  $startpos);  
    $myarray[]  =  substr($haystack,  $startpos  +  $startposlen,  $endpos  -  ($startpos  +  $startposlen));  
    $offset  =  $endpos;  
    if  (is_numeric(strpos($haystack,  $startpostext,  $offset)))  {  
      return  stripfromtextarray($haystack,$startpostext,  $endpostext,  &$myarray,  $offset);  
    }  
    else  {  
      return  $myarray;  
    }  
}  
?>  

The  following  is  an  example  of  the  use  of  these  functions  
<?php  
$filetitle  =  stripfromtext  ($content,  "<P  CLASS=title>",  "</  P>");  

//  and  
$rightmenuarray  =  stripfromtextarray($content,  "<P  CLASS=subtitle>",  "</  P>");  

foreach  ($rightmenuarray  as  $rm)  {$rightmenu.=$rm."<br>";}  
?>  
anonymous  dot  coward  at  slashdot  dot  org
21-Sep-2002  06:19  
Even  simpler  method  to  get  around  that  zero/false  headache:

if  (strpos('  '.$string,$substring)  >  1)
{
    echo('substring  present!');
}

Simly  add  a  space  to  your  string  being  tested.  Your  first  real  string  position  then  becomes  1,  and  zero  really  means  "string  not  found".  Please  adjust  your  position  formulas  accordingly  (substract  1).  
http://cm.zetyx.net/
18-Sep-2002  04:48  
About  issue:
Zero  (0)  is  not  a  false  result;  it  is  a  valid  answer.  The  function  returns  0  because  "abc"  does  indeed  contain  "abc"  and  the  first  occurence  of  the  target  string  starts  at  position  0.
Use  ===  to  test  if  the  function  returned  true  or  false.

Try  my  simple  and  easy  way  for  use  at  several  PHP  version.

$buf  =  "When  doves  cry.";
$chk  =  "Wh";
if  (strpos(  "#$%".$buf,  $chk))  {  return  TRUE;  }
else  {  return  FALSE;  }  
one  at  groobo  dot  com
16-Aug-2002  05:04  
You  all  know  it  probably,  but  it  is  quicker  to  use  strpos()  function  to  check  an  existence  of  a  character  in  a  string,  instead  of  regular  expressions.  
dont  at  spam  dot  net
24-Jul-2002  11:14  
To:  redeagle@chello.nl

Zero  (0)  is  not  a  false  result;  it  is  a  valid  answer.  The  function  returns  0  because  "abc"  does  indeed  contain  "abc"  and  the  first  occurence  of  the  target  string  starts  at  position  0.
Use  ===  to  test  if  the  function  returned  true  or  false.  
redeagle  at  chello  dot  nl
24-Jul-2002  12:39  
I've  just  did  a  test  using  strpos:
-
$test  =  strpos("abc",  "abc");
echo($test);
-
Note  that  $test  will  return  zero  (false)  if  the  seccond  parameter  is  the  same  as  the  first  parameter.  
schofiel  at  cs  dot  ualberta  dot  ca
19-Jul-2002  04:46  
Only  0  is  false  in  PHP  non-zero  is  postive
so  -2  could  be  a  true.

Since  they  can't  use  zero  becuase  it  is  in
the  range  of  possible  correct  positions  within
a  string.

So  do  the  type  check  against  false  explicity
to  prevent  odd  behavior  
jjrocket  at  yahoo  dot  com
04-May-2002  05:22  
It  may  be  obvious  to  most,  but  the  number  returned  by  strpos  will  be  the  position  in  haystack  at  which  the  string  needle  starts.  

For  example  if  haystack  is  "Now  is  the  time"  and  needle  is  "Now",  then  strpos  will  return  0,  not  2.  
martin  at  netimage  dot  dk
19-Apr-2002  11:54  
I  use  this

$a=strpos($haystack,$needle,$offset);

if($a!==false)    #  note  the  check  for  type  equivalence
//  found
else
//  not  found  
soletan  at  toxa  dot  de
10-Feb-2002  10:28  
Better  to  use  the  original  example  from  reference  part  for  checking,  if  strpos  failed  or  not  with  version  before  4.03b.

When  pos  is  an  integer  and  is  interpreted  as  boolean  false  (so  it  is  0)  strpos  FOUND  something  immediately  at  the  haystack's  beginning  ...  
maharj  at  DONTSPAMutu  dot  fi
14-Jan-2002  08:51  
I'm  not  sure  if  this  is  common,  but  I'll  take  an  example:

$str="123456test7890";

If  I  do:
for($i=0;$i<strpos($str,  "te");$i++)
    print  $str[$i];
print  "Hey  mon";
for($i=strpos($str,"st")+2;$i<strlen($str);$i++)
    print  $str[$i];

on  the  second  loop  the  strpos()  returns  something,  that  is  not  true.  (pos=2  or  something).

Solution:  Before  for:s  take  the  boundaries  to  variables  like:
$startPos=strpos($str,  "te");
$endPos=strpos($str,  "st")+2;
anduse  them  in  for-loops

Yes,  I  know  I  can  ereg("(.*)test(.*)",$str,$parm)  but  I  just  came  across  this...

The  PHP  version  I'm  using  is  4.0.4pl1

:)Mikko  
nmmm  at  nmmm  dot  nu
08-Jan-2002  10:44  
if  you  want  to  check  if  a  string  includes  some  character,  you  may  use  code  like  this  ('x'  is  in  position  0  in  the  string  so  if  $c  is  'x'  if  structure  will  return  false  :)

$c='5';
$s='01234567890';
if  (strpos($s,  'x'.$c))
      echo  "$c  is  a  number!";  
Michael-Rudel  at  gmx  dot  de
22-Nov-2001  11:01  
The  example  above  for  versions  older  than  4.0b3  should  check  for  integer,  since  strpos  returns  an  integer,  not  a  string.  So  it  should  read:  

//  in  versions  older  than  4.0b3:  
$pos  =  strpos($mystring,  "b");  
if  (is_integer($pos)  &&  !$pos)  {  
      //  not  found...  
}  

2062 view

4.0 stars