The Situation:
I wanted to return TRUE if strpos returned position 0, and only position 0, without the added overhead of preg_match.
The Solution:
As PHP treats 0 (zero) as NULL, and strpos returns the int 0 (but not NULL), I used type casting and the "===" comparison operator (as it compares types) to resolve my issue.
<?php
$hayStack = "dbHost";
$needle = "db"
$needlePos = strpos($hayStack, $needle);
if((string)$needlePos === (string)0) {
echo "db is in position zero";
} else {
echo "db is NOT in position zero";
}
?>
Returns:
db is in position zero
<?php
$hayStack = "another_db_host";
$needle = "db"
$needlePos = strpos($hayStack, $needle);
if((string)$needlePos === (string)0) {
echo "db is in position zero";
} else {
echo "db is NOT in position zero";
}
?>
This returns:
db is in NOT position zero
strpos
(PHP 4, PHP 5)
strpos — Find position of first occurrence of a string
Description
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used.
Parameters
- haystack
-
The string to search in
- needle
-
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
- offset
-
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack .
Return Values
Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Examples
Example #1 Using ===
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Example #2 Using !==
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// The !== operator can also be used. Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>
Example #3 Using an offset
<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>
Notes
Note: This function is binary-safe.
strpos
28-Dec-2008 01:48
18-Nov-2008 02:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.
<?php
/**
* strposall
*
* Find all occurrences of a needle in a haystack
*
* @param string $haystack
* @param string $needle
* @return array or false
*/
function strposall($haystack,$needle){
$s=0;
$i=0;
while (is_integer($i)){
$i = strpos($haystack,$needle,$s);
if (is_integer($i)) {
$aStrPos[] = $i;
$s = $i+strlen($needle);
}
}
if (isset($aStrPos)) {
return $aStrPos;
}
else {
return false;
}
}
?>
28-Oct-2008 09:20
@samundra dot shr at gmail dot com
You can simplify this a lot by using str_replace to do the work for you
<?php
$filename=$_POST['filename'];
if(!$fpin=@fopen($filename,"r"))
{
print "<b>Error ! File Doesn't Exists</b>";
exit();
}
$text='';
while(!feof($fpin))
{
$text.=fread($fpin,1024);
}
$newtext = str_replace(array("\n", "\r"), '', $text);
$fp=fopen("sample.txt","wb+");
fwrite($fp,$newtext);
fclose($fp);
print "File Changed Successfully.";
?>
Or simply using php5 and not needing to do all the fread/fwrite
<?php
$filename=$_POST['filename'];
if(file_exists($filename)) {
file_put_contents('sample.txt', str_replace(array("\n", "\r"), '', file_get_contents($filename)));
}
else {
print "<b>Error ! File Doesn't Exists</b>";
}
?>
23-Oct-2008 03:19
careful that when you put a strpos in an if statement that you take note that if the string is in the 0 position it will return false, causing your control structure to think its not in the string.
28-Sep-2008 08:40
This is the code,I wrote today, I wanted to strip all the newlines, and format the output in a single line so as to lower the filesize of my php source files.
<?php
/****************************************
@ Code By : Samundra Shrestha
@ Dated : September 28,2008
P.S. Remember to remove all single line comments from the source file
otherwise the file may get corrupted.
******************************************/
if(!isset($_POST['change']) || !isset($_POST['filename']))
{
print "<b>".strtoupper("Paste the fullpath of the file")."</b>";
print "<form name='FrmChange' method='post' action='".$_SERVER['PHP_SELF']."'>";
print "<input type='textbox' name='filename' size='50px' maxlength='255'>";
print "<input type='submit' name='change' value='Start'>";
print "</form>";
}
else
{
$filename=$_POST['filename'];
if(!$fpin=@fopen($filename,"r"))
{
print "<b>Error ! File Doesn't Exists</b>";
exit();
}
$text="";
$i=0;
/*Put the contents of file into the string*/
while(!feof($fpin))
{
$text.=fread($fpin,1024);
}
$count=strlen($text);
$pos=strpos($text,"\n"); //Gives the First occurence of newline
while($i<$count)
{
if($i<$pos-1)
{
$newtext.=$text{$i}; //C Style of String Indexing
}
else
{
$pos=strpos($text,"\n",$i+1);
}
$i++;
}
$newtext.="?>"; //necessary as somehow it is removed from the original source file.
$fp=fopen("sample.txt","wb+");
fwrite($fp,$newtext);
fclose($fp);
print "File Changed Successfully.";
}
?>
The resultant code is all in one new line saved in file sample.txt
I hope, this comes handy to someone.
Cheers,
Samundra Shrestha
http://www.samundra.com.np
19-Sep-2008 08:17
here's a php implementation of stdc++ string class find_first_of using strpos.
<?php
function find_first_of($haystack, $needlesAsString, $offset=0)
{
$max = strlen($needlesAsString);
$index = strlen($haystack)+1;
for($ii=0; $ii<$max;$ii++){
$result = strpos($haystack,$needlesAsString[$ii], $offset);
if( $result !== FALSE && $result < $index)
$index = $result;
}
return ( $index > strlen($haystack)? FALSE: $index);
}
?>
Example:
<?php
$test="Ralph: One of these days, Alice!!";
$look_for=":!,"; // punctuation marks
$ss = 0;
while( $answer=find_first_of($test,$look_for,$ss) ) {
echo $answer . "\n";
$ss = $answer+1;
}
?>
This prints out:
5
24
31
32
22-Aug-2008 11:01
Hi,
Chuzasoft Inc : maybe I haven't understood your goal clearly, but I think there is a faster way to determinate whether a pattern is contained in a string (like using the " LIKE '%bla bla%' " in SQL).
You should read about "Regular Expression" (powerfull string operations are allowed using it) : http://fr.php.net/manual/en/book.pcre.php
Your example, it should be written like this :
<?
$myString = "Hi, this is good!";
$srchStrg = ".*thi.* goo.*";
$srchRes = preg_match("/$searchThis/", $myString);
if ( $searchResult != 0 )
echo "TRUE: string has been found :-)";
else
echo "FALSE: string wasn't found :'-(";
?>
Sincerely
05-Aug-2008 09:16
Hi! Don't you people miss the pretty comparison operator 'LIKE' from mySql in PHP??.
I've made this funtion to emulate that method. It's for search a match string into another String
using the '%' caracter just like you do un the LIKE syntax.
For example:
<?php
$mystring = "Hi, this is good!";
$searchthis = "%thi% goo%";
$resp = milike($mystring,$searchthis);
if ($resp){
echo "milike = VERDADERO";
} else{
echo "milike = FALSO";
}
?>
Will print:
milike = VERDADERO
and so on...
this is the function:
<?php
function milike($cadena,$busca){
if($busca=="") return 1;
$vi = split("%",$busca);
$offset=0;
for($n=0;$n<count($vi);$n++){
if($vi[$n]== ""){
if($vi[0]== ""){
$tieneini = 1;
}
} else {
$newoff=strpos($cadena,$vi[$n],$offset);
if($newoff!==false){
if(!$tieneini){
if($offset!=$newoff){
return false;
}
}
if($n==count($vi)-1){
if($vi[$n] != substr($cadena,strlen($cadena)-strlen($vi[$n]), strlen($vi[$n]))){
return false;
}
} else {
$offset = $newoff + strlen($vi[$n]);
}
} else {
return false;
}
}
}
return true;
}
?>
Good luck!
27-Jun-2008 10:51
Paul: May it be that the ! operator is evaluated before the ===? In this case, the return value of strpos (0 in the described case) would be implicitly converted to bool (value true because 0 converts to false). Then, true === false is evaluated to false.
18-Jun-2008 12:48
I wasn't aware of the !== operator, only the === for false. I was using this code on strpos:
while( ! ($start=@strpos($source,$startTag,$end)) === false)
This gave a false if the string was found at position 0, which is weird.
However using
while(($start=@strpos($source,$startTag,$end)) !== false)
Gives no such error and seems to work correctly
26-May-2008 03:19
Hello! I was founding a function, which finds any occurence of a string (no: first occurence). I wasn't, so I maked this function! It may be very useful.
<?php
int strnpos(string $haystack, mixed $needle, int $occurence);
?>
Example:
<?php
strnpos("I like the bananas. You like coke. We like chocolate.", "like", 2); // 24
?>
Here's code of this function:
<?php
function strnpos($base, $str, $n)
{
if ($n <= 0 || intval($n) != $n || substr_count($base, $str) < $n) return FALSE;
$str = strval($str);
$len = 0;
for ($i=0 ; $i<$n-1 ; ++$i)
{
if ( strpos($base, $str) === FALSE ) return FALSE;
$len += strlen( substr($base, 0, strpos($base, $str) + strlen($str)) );
$base = substr($base, strpos($base, $str) + strlen($str) );
}
return strpos($base, $str) + $len;
}
?>
02-Apr-2008 02:17
This might be useful.
class String{
//Look for a $needle in $haystack in any position
public static function contains(&$haystack, &$needle, &$offset)
{
$result = strpos($haystack, $needle, $offset);
return $result !== FALSE;
}
//intuitive implementation .. if not found returns -1.
public static function strpos(&$haystack, &$needle, &$offset)
{
$result = strpos($haystack, $needle, $offset);
if ($result === FALSE )
{
return -1;
}
return $result;
}
}//String
20-Feb-2008 04:08
Refereing to my last note.
It wasn't correct! As ctype_digit only evaluates strings.
(string) true / false will still be 0 / 1.
is_int(); is the correct function!
18-Feb-2008 07:22
As mentioned before....
0 === false
0 == false
1 === true
etc...
I found it very usefull to use ctype_digit(); with this function!
<?php
$string = 'whatever!#%@^% is going on...'; //correct
//$string = 'whatever? is going on...'; //false char 8
//ctype_digit only works on strings so type cast...
if(ctype_digit((string) strpos($string, '?'))){
echo 'found at least one...<br/>'.PHP_EOL;
}
else{
echo 'no char index retrieved... <br/>'.PHP_EOL;
}
?>
12-Jan-2008 01:02
There's actually a fourth conceivable test for "any position other than 0" --
ADD:
!= "" (disrecommended as highly confusing)
This then makes the final paragraph inaccurate (one case where comparing to "" is meaningful). It should just be removed entirely -- too much unneeded detail on a tangent anyway.
12-Jan-2008 12:45
WARNING
As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.
To know that a substring is absent, you must use:
=== FALSE
To know that a substring is present (in any position including 0), you can use either of:
!== FALSE (recommended)
> -1 (note: or greater than any negative number)
To know that a substring is at the start of the string, you must use:
=== 0
To know that a substring is in any position other than the start, you can use any of:
> 0 (recommended)
!= 0 (note: but not !== 0 which also equates to FALSE)
!= FALSE (disrecommended as highly confusing)
Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
24-Dec-2007 01:45
WARNING: The documentation says:
"Use the === operator for testing the return value of this function"
but it should say:
"Use '!== false' or '=== false' for testing the return value of this function"
Therefore to test if a needle occurst in a hastack do this:
if ( strpos($haystack, $needle) !== false){
echo 'found needle in haystack!';
}
Using '=== true' or '!== true' or '== true' or '== false' will all return the wrong value when the needle is found in the haystack.
using ' >= 0 ' returns the wrong value when the needle is not found in the haystack.
By "wrong value" I mean a value that is counter-intuitive but is never-the-less correct according to the weird way in which strpos has been coded. Why on earth didn't they just return -1 if the needle was not found? Then we could just test for >= 0
Here's a full list of the value returned:
(strpos("bbb", "aaa") >= 0) returns true EXPECTED FALSE
(strpos("bbb", "aaa") == true) returns false expected false
(strpos("bbb", "aaa") == false) returns true expected true
(strpos("bbb", "aaa") === true) returns false expected false
(strpos("bbb", "aaa") === false) returns true expected true
(strpos("bbb", "aaa") !== false) returns false expected false
(strpos("bbb", "aaa") !== true) returns true expected true
(strpos("aaa", "aaa") >= 0) returns true expected true
(strpos("aaa", "aaa") == true) returns false EXPECTED TRUE
(strpos("aaa", "aaa") == false) returns true EXPECTED FALSE
(strpos("aaa", "aaa") === true) returns false EXPECTED TRUE
(strpos("aaa", "aaa") !== false) returns true expected true
(strpos("aaa", "aaa") === false) returns false expected false
(strpos("aaa", "aaa") !== true) returns true EXPECTED FALSE
31-Oct-2007 11:19
A further implementation of the great rstrpos function posted in this page. Missing some parameters controls, but the core seems correct.
<?php
// Parameters:
//
// haystack : target string
// needle : string to search
// offset : which character in haystack to start searching, FROM THE END OF haystack
// iNumOccurrence : how many needle to search into haystack beginning from offset ( i.e. the 4th occurrence of xxx into yyy )
function rstrpos ($haystack, $needle, $offset=0, $iNumOccurrence=1)
{
//
$size = strlen ($haystack);
$iFrom = $offset;
$iLoop = 0;
//
do
{
$pos = strpos (strrev($haystack), strrev($needle), $iFrom);
$iFrom = $pos + strlen($needle);
}
while ((++$iLoop)<$iNumOccurrence);
//
if($pos === false) return false;
//
return $size - $pos - strlen($needle);
}
?>
14-Oct-2007 01:49
str_replace evaluates its arguments exactly once.
for example:
<?php
$page = str_replace("##randompicture##", getrandompicture(), $page);
?>
will call getrandompicture() once, ie it will insert the same random picture for each occurrence of ##randompicture## :(
Here is my quick and dirty workaround:
<?php
function add_random_pictures($text) {
while (($i = strpos($text, "##randompicture##")) !== false) {
$text = substr_replace($text, getrandompicture(), $i, strlen("##randompicture##"));
}
return $text;
}
$page = add_random_pictures($page);
?>
09-Sep-2007 11:51
Just to be clear: unlike stripos(), strpos() is case-sensitive.
28-Aug-2007 01:05
@Wagner Christian:
Yes, there are better methods. The best is to just cast is. You cast like this:
<?php
$id = 1;
$string = (string) $id;
?>
If you var_dump() $string now you get the following output:
string(1) "1"
This is the recommended method. You're example should look like this then:
<?php
$id = 1;
$my_text = "hel124lo";
$first_position =strpos($my_text , (string) $id);
?>
17-Aug-2007 10:11
If you plan to use an integer as needle you need first to convert your integer into a String else it's not going to work.
For exemple :
<?php
$id = 1;
$my_text = "hel124lo";
$first_position =strpos($my_text ,substr($id,0));
?>
There are for sure some another solutions to convert an integer into a string in php.
15-May-2007 11:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.
<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
/*====================================================================
Function to scan a string for items encapsulated within a pair of tags
getStrsBetween(string, tag1, <tag2>, <offset>
If no second tag is specified, then match between identical tags
Returns an array indexed with the encapsulated text, which is in turn
a sub-array, containing the position of each item.
Notes:
strpos($needle,$haystack,$offset)
substr($string,$start,$length)
====================================================================*/
if( $s2 === false ) { $s2 = $s1; }
$result = array();
$L1 = strlen($s1);
$L2 = strlen($s2);
if( $L1==0 || $L2==0 ) {
return false;
}
do {
$pos1 = strpos($s,$s1,$offset);
if( $pos1 !== false ) {
$pos1 += $L1;
$pos2 = strpos($s,$s2,$pos1);
if( $pos2 !== false ) {
$key_len = $pos2 - $pos1;
$this_key = substr($s,$pos1,$key_len);
if( !array_key_exists($this_key,$result) ) {
$result[$this_key] = array();
}
$result[$this_key][] = $pos1;
$offset = $pos2 + $L2;
} else {
$pos1 = false;
}
}
} while($pos1 !== false );
return $result;
}
?>
26-Apr-2007 05:58
Here's a somewhat more efficient way to truncate a string at the end of a word. This will end the string on the last dot or last space, whichever is closer to the cut off point. In some cases, a full stop may not be followed by a space eg when followed by a HTML tag.
<?php
$shortstring = substr($originalstring, 0, 400);
$lastdot = strrpos($shortstring, ".");
$lastspace = strrpos($shortstring, " ");
$shortstring = substr($shortstring, 0, ($lastdot > $lastspace? $lastdot : $lastspace));
?>
Obviously, if you only want to split on a space, you can simplify this:
<?php
$shortstring = substr($originalstring, 0, 400);
$shortstring = substr($shortstring, 0, strrpos($shortstring, " "));
?>
Thanks to spinicrus (see above) I have sorted out a problem that was bugging me for ages. I have a routine in Etomite Content Management System that will display a set number of characters of a news item and invite visitors to "Read more".
Unfortunately the 400 character summary sometimes displayed a partial word at the end.
Using the following code based on spinicrus's exampleI have now overcome this.
#################################
#only full word at the end
$string=$rest;
$charToFind=" ";
$searchPos = $lentoshow;
$searchChar = '';
//
while ($searchChar != $charToFind) {
$newPos = $searchPos-1;
$searchChar = substr($string,$newPos,strlen($charToFind));
$searchPos = $newPos;
}
$rest=substr($string,0,$searchPos)." ";
################################
11-Apr-2007 02:35
If you want to check for either IE6 or 7 individually.
<?php
function browserIE($version)
{
if($version == 6 || $version == 7)
{
$browser = strpos($_SERVER['HTTP_USER_AGENT'], "MSIE ".$version.".0;");
if($browser == true)
{
return true;
}
else
{
return false;
}
else
{
return false;
}
?>
03-Apr-2007 06:57
this function returns the text between 2 strings:
function get_between ($text, $s1, $s2) {
$mid_url = "";
$pos_s = strpos($text,$s1);
$pos_e = strpos($text,$s2);
for ( $i=$pos_s+strlen($s1) ; ( ( $i < ($pos_e)) && $i < strlen($text) ) ; $i++ ) {
$mid_url .= $text[$i];
}
return $mid_url;
}
if $s1 or $s2 are not found, $mid_url will be empty
to add an offset, simply compare $pos_s to the offset, and only let it continue if the offset is smaller then $pos_s.
26-Jan-2007 08:23
Get text between $s1 and $s2, return an array contains every occurrence (based on code of old comment/s but with offset and without strtolower)
Sample:
$myDivsContent = getStrsBetween("<div","</div>",$myHtmlSrc);
Sample:
or...get rows for html table
...
...
//using TextBetween from old comment...
$aTable = TextBetween("<table","</table>",$myHtmlSrc);
$rows = getStrsBetween("<tr","</tr>",$aTable);
...
...
function getStrsBetween($s1,$s2,$s,$offset=0){
$result = array();
$index= 0;
$L1 = strlen($s1);
$found = false;
do{
if($L1>0){
$pos1 = strpos($s,$s1,$offset);
}
else {
$pos1=$offset;
}
if($pos1 !== false){
if($s2 == '')
$result[$index++]= substr($s,$pos1+$L1);
$pos2 = strpos(substr($s,$pos1+$L1),$s2,$L1);
if($pos2!==false){
$result[$index++]= substr($s,$pos1+$L1,$pos2);
$offset += $pos2 + strlen($s2);
}
else{
$pos1 = false;
}
}
}while($pos1 !== false);
return $result;
}
BUGs/Problems:
Function do not stop while $s1 is found in $s.
19-Jan-2007 09:15
Try this function to find the first position of needle before a given offset.
For example:
<?php
$s = "This is a test a is This";
$offset = strpos($s, "test");
strnpos($s, "is", $offset); // returns 17
strnpos($s, "is", -$offset); // returns 5
// Works just like strpos if $offset is positive.
// If $offset is negative, return the first position of needle
// before before $offset.
function strnpos($haystack, $needle, $offset=0)
{
if ($offset>=0)
$result=strpos($haystack, $needle, $offset);
else
{
$offset=strlen($haystack)+$offset;
$haystack=strrev($haystack);
$needle=strrev($needle);
$result=strpos($haystack, $needle, $offset);
if ($result!==false)
{
$result+=strlen($needle);
$result=strlen($haystack)-$result;
}
}
return $result;
}
?>
this is nice you are so excited but parsing href=" will never really work.
remember whitespaces
29-Dec-2006 09:30
I understand the excitement of "admin at xylotspace dot com." I wrote three functions that I use in EVERY website I develop. What they do is get the text between strings. I made them case-insensitive (for php < 5) using "strtolower." This would not be necessary if you used "stripos." Now the first function is close to what "admin at xylotspace dot com" wrote, but does not have the position element. It also will return an empty string if no substring was found. If you want to get the title of an HTML document use:
TextBetween('<title>','</title>',$content);
The second function was revolutionary for me, because it gets an array of items between pairs of strings. So, with that I can grab most XML lists, or get all the links or images in a document. All the links in a document could be found using:
TextBetweenArray('href="','"',$content);
The third is less used, but is useful to process an array and get substrings within each record.
//-----GET TEXT BETWEEN STRINGS------
function TextBetween($s1,$s2,$s){
$s1 = strtolower($s1);
$s2 = strtolower($s2);
$L1 = strlen($s1);
$scheck = strtolower($s);
if($L1>0){$pos1 = strpos($scheck,$s1);} else {$pos1=0;}
if($pos1 !== false){
if($s2 == '') return substr($s,$pos1+$L1);
$pos2 = strpos(substr($scheck,$pos1+$L1),$s2);
if($pos2!==false) return substr($s,$pos1+$L1,$pos2);
}
return '';
}
//-----GET ARRAY TEXT BETWEEN STRINGS------
function TextBetweenArray($s1,$s2,$s){
$myarray=array();
$s1=strtolower($s1);
$s2=strtolower($s2);
$L1=strlen($s1);
$L2=strlen($s2);
$scheck=strtolower($s);
do{
$pos1 = strpos($scheck,$s1);
if($pos1!==false){
$pos2 = strpos(substr($scheck,$pos1+$L1),$s2);
if($pos2!==false){
$myarray[]=substr($s,$pos1+$L1,$pos2);
$s=substr($s,$pos1+$L1+$pos2+$L2);
$scheck=strtolower($s);
}
}
} while (($pos1!==false)and($pos2!==false));
return $myarray;
}
//-----GET SUBTEXT IN ARRAY ITEMS------
function SubTextBetweenArray($s1,$s2,$myarray){
for ($i=0; $i< count($myarray); $i++)
{$myarray[$i]=TextBetween($s1,$s2,$myarray[$i]);}
return $myarray;
}
18-Dec-2006 11:31
I've been looking at previous posts and came up with this function to find the start and end off an certain occurance or all occurances of needle within haystack.
I've made some minor tweaks to the code itself, like counting the length of needle only once and counting the result set array instead of using a count variable.
I also added a length parameter to the result set to use in a following substr_replace call etc...
<?php
function strpos_index($haystack = '',$needle = '',$offset = 0,$limit = 99,$return = null)
{
$length = strlen($needle);
$occurances = array();
while((($count = count($occurances)) < $limit) && (false !== ($offset = strpos($haystack,$needle,$offset))))
{
$occurances[$count]['length'] = $length;
$occurances[$count]['start'] = $offset;
$occurances[$count]['end'] = $offset = $offset + $length;
}
return $return === null ? $occurances : $occurances[$return];
}
?>
03-Dec-2006 09:10
Small improvement on the efforts of others:
<?php
function strpos_all($hs_haystack, $hs_needle, $hn_offset = 0, $hn_limit = 0) {
$ha_positions = array();
$hn_count = 0;
while (false !== ($pos = strpos($hs_haystack, $hs_needle, $hn_offset)) && ($hn_limit == 0 || $hn_count < $hn_limit)) {
$ha_positions[] = $pos;
$hn_offset = $pos + strlen($hs_needle);
++$hn_count;
}
return $ha_positions;
}
function preg_pos($hs_pattern, $hs_subject, &$hs_foundstring, $hn_offset = 0) {
$hs_foundstring = NULL;
if (preg_match($hs_pattern, $hs_subject, $ha_matches, PREG_OFFSET_CAPTURE, $hn_offset)) {
$hs_foundstring = $ha_matches[0][0];
return $ha_matches[0][1];
}
else {
return FALSE;
}
}
function preg_pos_all($hs_pattern, $hs_subject, &$ha_foundstring, $hn_offset = 0, $hn_limit = 0) {
$ha_positions = array();
$ha_foundstring = array();
$hn_count = 0;
while (false !== ($pos = preg_pos($hs_pattern, $hs_subject, $hs_foundstring, $hn_offset)) && ($hn_limit == 0 || $hn_count < $hn_limit)) {
$ha_positions[] = $pos;
$ha_foundstring[] = $hs_foundstring;
$hn_offset = $pos + 1; // alternatively: '$pos + strlen($hs_foundstring)'
++$hn_count;
}
return $ha_positions;
}
print_r(preg_pos_all('/s...s/', "she sells sea shells on the sea floor", $ha_matches));
print_r($ha_matches);
?>
14-Oct-2006 07:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:
<?php
function strpos_reverse_way($string,$charToFind,$relativeChar) {
//
$relativePos = strpos($string,$relativeChar);
$searchPos = $relativePos;
$searchChar = '';
//
while ($searchChar != $charToFind) {
$newPos = $searchPos-1;
$searchChar = substr($string,$newPos,strlen($charToFind));
$searchPos = $newPos;
}
//
if (!empty($searchChar)) {
//
return $searchPos;
return TRUE;
}
else {
return FALSE;
}
//
}
?>
27-Sep-2006 04:33
Yay! I came up with a very useful function. This finds a beginning marker and an ending marker (the first after the beginning marker), and returns the contents between them. You specify an initial position in order to tell it where to start looking. You can use a while() or for() loop to get all occurence of a certain string within a string (for example, taking all hyperlinks in a string of HTML code)...
function get_middle($source, $beginning, $ending, $init_pos) {
$beginning_pos = strpos($source, $beginning, $init_pos);
$middle_pos = $beginning_pos + strlen($beginning);
$ending_pos = strpos($source, $ending, $beginning_pos + 1);
$middle = substr($source, $middle_pos, $ending_pos - $middle_pos);
return $middle;
}
For example, to find the URL of the very first hyperlink in an HTML string $data, use:
$first_url = get_middle($data, '<a href="', '"', 0);
It's done wonders for scraping HTML pages with certain tools on my website.
25-Aug-2006 03:07
To thepsion5 at hotmail dot com:
Please mind the warning part of the documentation!
Your function won't work on $Haystack s starting with $needle.
Here's a solution for that:
<?
function findAllOccurences($Haystack, $needle, $limit=0)
{
$Positions = array();
$currentOffset = 0;
$count=0;
while(($pos = strpos($Haystack, $needle, $offset))!==false && ($count < $limit || $limit == 0))
{
$Positions[] = $pos;
$offset = $pos + strlen($needle);
$count++;
}
return $Positions;
}
?>
10-Aug-2006 09:38
Simple function to determine if a needle occurs in a haystack
function is_substr($needle, $haystack){
$pos = strpos($haystack, $needle);
if ($pos === false) {
return false;
} else {
return true;
}
}
07-Aug-2006 07:57
I created this little function based on the one posted by chasesan at gmail dot com; It find all occurences of a string within another string and returns their positions as an array:
<?PHP
function findAllOccurences($Haystack, $needle, $limit=0)
{
$Positions = array();
$currentOffset = 0;
$count=0;
while(($pos = strpos($Haystack, $needle, $offset)) && ($count < $limit || $limit == 0))
{
$Positions[] = $pos;
$offset = $pos + strlen($needle);
$count++;
}
return $Positions;
}
?>
I hope this helps someone :)
24-Jul-2006 08:24
I finally figured out how to use this function correctly (and efficiently) if you want to test for a needle that may start at the beginning of haystack, simply use
if (strpos($haystack, $needle) === 0)) {
do stuff here..
}
someone else mentioned that you needed to assign a variable first and test to make sure that it was === true first.. That is not needed
19-Jul-2006 02:26
Im sure there are more efficient methods of this, but i use this alot when dealing with rss and was proud of it.
<?
function data_from_element($needle,$haystack,$tags=FALSE) { // Expects two Strings, returns Array
$needle_start = "<".$needle.">"; $needle_end = "</".$needle.">";
$array = array(); $pos_start = 0;
while(($pos_start = strpos($haystack,$needle_start,$pos_start)) !== false) {
$pos_end = strpos($haystack,$needle_end,$pos_start);
if($tags) $array[] = substr($haystack,$pos_start,$pos_end-$pos_start+strlen($needle_end));
else $array[] = substr($haystack,$pos_start + strlen($needle_start),$pos_end - $pos_start - strlen($needle_start));
$pos_start++;
}
return $array;
}
d
//example
$rss = '<?xml version="1.0"?> <rss version="2.0"> <channel> <title>Example RSS</title> <description>Example RSS Description</description> <link>http://example.com/rss/</link> <item> <title>Example RSS 1</title> <link>http://example.com/rss/1.html</link> <description>Example 1</description> </item> <item> <title>Example RSS 2</title> <link>