strstr

(PHP 3, PHP 4, PHP 5)

strstr --  Находит первое вхождение подстроки

Описание

string strstr ( string haystack, string needle )

Возвращает подстроку строки haystack начиная с первого вхождения needle до конца строки.

Если подстрока needle не найдена, возвращает FALSE.

Если needle не является строкой, он приводится к целому и трактуется как код символа.

Замечание: Эта функция учитывает регистр символов. Для поиска без учета регистра используйте stristr().

Пример 1. Пример использования strstr()

<?php
$email
= 'user@example.com';
$domain = strstr($email, '@');
echo
$domain; // выводит @example.com
?>

Замечание: Если нужно лишь определить, встречается ли подстрока needle в haystack, используйте функцию strpos(), которая работает быстрее и потребляет меньше памяти.

С версии PHP 4.3.0 strstr() безопасна для обработки данных в двоичной форме.

См. также описание функций ereg(), preg_match(), stristr(), strpos(), strrchr() и substr().



strstr
repley at freemail dot it
21-May-2006 09:55
To explode around first occurrence of a character in a string (inclusive or NOT inclusive), using strstr and strstr_reverse.

<?
//strxstr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxstr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(
strrpos($haystack, $needle)){
      
//Everything before first $needle in $haystack.
      
$left substr($haystack, 0, strpos($haystack, $needle) + $l_inclusive);
 
      
//Switch value of $r_inclusive from 0 to 1 and viceversa.
      
$r_inclusive = ($r_inclusive == 0) ? 1 : 0;
 
      
//Everything after first $needle in $haystack.
      
$right substr(strstr($haystack, $needle), $r_inclusive);
 
      
//Return $left and $right into an array.
      
$a = array($left, $right);
       return
$a;
   }else{
       return
false;
   }
}

//start test
$haystack = "http://www....unknown....com.biz......";
$needle = ".";
$l_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode
$r_inclusive = 1; //1 for inclusive mode, 0 for NOT inclusive mode

$a = strxstr($haystack, $needle, $l_inclusive, $r_inclusive);
if(
$a){echo "Left: <strong>" . $a[0] . "</strong><br />Right: <strong>" . $a[1] . "</strong>";}else{echo "Failed!";}
//end test
?>

To explode around last occurrence of a character in a string, for example to get filename and extension separately into an array, use strxchr(): manual/en/function.strrchr.php
onuryerlikaya at hotmail dot com
25-Jan-2006 12:00
<?php
$piece   
= 6;
$data    = 'djhfoldafg9d7yfr3nhlrfkhasdfgd';
$piece1    = substr($data,0,$piece);
$piece2    = strstr($data,substr($data,$piece,$piece));
echo
'$piece1 :'.$piece1; // $piece1 :djhfol
echo "<br>";
echo
'$piece2 :'.$piece2; // piece2 :dafg9d7yfr3nhlrfkhasdfgd
?>

You can piece your string which given at $piece variable.
always_sleepz0r at removethisyahoo dot co dot uk
14-Jan-2006 11:38
//this is my little version

function rdir($d_d, $filter = null) {   
   $d = dir($d_d);while(false !== ($entry = $d->read())) {
     if ($entry!=".." && $entry!="." && $filter==null || true==stristr($entry, $filter)){ if (!is_dir($entry)) {
     $ret_arr['f'][]=$entry;}else{$ret_arr['d'][]=$entry;
   }}}$d->close();return $ret_arr;}

//usage:
$d="folder";

$dd=rdir($d);
//will return array with all files and folder names

$dd=rdir($d, "requiredneedle");
//will return array with only file/folder names containing "requiredneedle".

//$dd['f'] = files and $dd['d'] = folders
echo "<pre>";print_r($dd);echo "</pre>";
nospam AT thenerdshow.com
15-Nov-2005 04:20
It is a good practice to ensure dropdown menu submissions contain ONLY expected values:

$i=(isset($_POST['D1']))?$_POST['D1']:$o="Monday";
if (!stristr('Monday Tuesday Wednesday Thursday Friday Saturday Sunday',$i)) die();
(do database query)

This should protect against all known and unknown attacks, injection, etc.

User submitted should be cleaned through other functions.  See info under mysql_query
06-Jun-2005 09:13
suggestion for [leo dot nard at free dot fr]:
to be able to cut the string without having the html entities being cut in half, use this instead:

<?php

$oldstr
= "F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandinaviska (eller Franska, f&ouml;r den delen) tecken, kan man g&ouml;ra s&aring;h&auml;r...";

$length = 50;

# First, first we want to decode the entities (to get them as usual chars), then cut the string at for example 50 chars, and then encoding the result of that again.

# Or, as I had it done, in one line:
$newstr = htmlentities(substr(html_entity_decode($oldstr), 0, $length));
$newstr2 = substr($oldstr, 0, $length);
# It's not quite as much code as the snippet you've coded to remove the half-portions... ;)
# Hopefully somebody finds this useful!
echo "Without the decode-encode snippet:
$newstr2

With the decode-encode snippet:
$newstr"
;
?>

The above outputs this:

Without the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&ar

With the decode-encode snippet:
F&ouml;r att klippa av en str&auml;ng som inneh&aring;ller skandin

First post in this db ;)
Best regards, Mikael Rnn, FIN
leo dot nard at free dot fr
24-May-2005 02:12
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "" to a string of size 10, you would get: "&agrave;&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

function cut_html($string)
{
   $a=$string;

   while ($a = strstr($a, '&'))
   {
       echo "'".$a."'\n";
       $b=strstr($a, ';');
       if (!$b)
       {
           echo "couper...\n";
           $nb=strlen($a);
           return substr($string, 0, strlen($string)-$nb);
       }
       $a=substr($a,1,strlen($a)-1);
   }
   return $string;
}
rodrigo at fabricadeideias dot com
22-Apr-2005 12:55
A better solution for nicolas at bougues dot net's problem below is to use

<?
strstr
("0", "0") === FALSE
?>

instead of

<?
strstr
("0", "0") == FALSE
?>

or

<?
is_string
(strstr ("0", "0"))
?>
robbie [at] averill [dot] co [dot] nz
18-Mar-2005 05:07
With regard to the below comment

<?php
$filename
= "funnypicture.jpg";
$type = str_replace('.','',strstr($filename, '.'));
echo
$type; // jpg
?>

This gets the file extension into the variable $type, not the file type.

To get the file type, use filetype(), or to get the MIME content type, use mime_content_type().

<?php
$filename
= "funnypicture.jpg";
$ext = str_replace('.','',strstr($filename, '.'));
$type = filetype($filename);
$mime = mime_content_type($filename);
echo
$ext;    // jpg
echo $type// file
echo $mime; //  image/jpeg
?>
redzia
08-Feb-2005 07:54
Example usage of fopen to remove line containing a key string
<?

$key
= "w3ty8l";

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
     if (!
strstr($line,$key)) //look for $key in each line
          
fputs($f,$line); //place $line back in file
}
fclose($f);

?>
steve at alittlefinesse dot com
03-Sep-2004 08:55
// I needed to find the content between 2 chrs in a string and this was the quickest method I could find.

function SeekVal($str_in) {

$tween="";  // not needed but good practise when appending
$chr1='[';
$chr2=']';

for ($i=strpos($str_in, $chr1);$i<strpos($str_in, $chr2);$i++)
  $tween=$tween+$str_in[$i];

return $tween;   
}
Ami Hughes (ami at mistress dot name)
22-Apr-2004 09:02
Because I was working with two different sets of variables and wanted to combine the result into a decimal format, I needed to strip the zero before the decimal.  As an added bonus, this will strip anything before a decimal (or period), which might be useful for other things.  So, if you are trying to combine apples and oranges like I was, or whatever, try this.  =)

<?php
$number
= '0.529';
strstr($number,'.');
echo
$number; // returns .529
?>
schultz at widescreen dot ch
01-Apr-2004 02:22
a nice way to decide wether a string starts with a certain prefix, one can use this condition...

$url = 'http://www.widescreen.ch';
$isUrl = ( strstr($url,'http://') == $url );

have  fun!
Lars
giunta dot gaetano at sea-aeroportimilano dot it
23-Feb-2004 06:16
Note to Rolf's post: if the needle is NOT found, the function proposed will truncate the last char of the string!
Romuald Brunet
21-Jan-2004 12:25
Regarding the note of the manual concerning the speed of strstr against strpos, for people who wants to check a needle occurs within haystack, it apprears that strstr() is in facts faster than strpos().

Example:
<?php
// [VERY] Quick email check:
if ( strstr("email@domain.tld", "@") ) {
// Ok
}
?>

is faster than

<?php
if ( strpos("email@domain.tld", "@") !== FALSE ) {
// Ok
}

Without using the true equality with !==, strpos() is faster. But then if the haystack starts with needle the condition whould not be met.
teezee
14-Mar-2003 03:08
//Checking and using the above string can be done much easier:

$data="ID: 1, Rolf Winterscheidt, and so on";
$data_array = explode(",",$data);

//will return an array:
 $data[0] = ID: 1
 $data[1] =  Rolf Winterscheidt
 $data[2] =  and so on
rolf dot winterscheidt at rowitech dot de
07-Mar-2003 04:02
Get the first part of the string can be so easy:

$data="ID: 1, Rolf Winterscheidt, and so on";
$id=substr($data, 0 , strpos($data, ",")-1);
-> $id is now "ID: 1"

Best regards,
Rolf
crypto at notup2u dot net
01-Mar-2003 05:44
I've noticed that :

$string = substr($string, 0, strpos($string,$separat));

returns the first par of the string (before $separat) only if there is $separat in the string !

But

$string = substr($string, 0, strlen($string)-strlen (strstr ($string,$separat)));

works anyway ...

That can be useful !

/Crypto
php at silisoftware dot com
14-Feb-2003 03:37
PHP versions before 4.3.0 (tested on 4.2.2 and 4.2.3) return the $haystack from $needle only up to the first null character. So for example:

$string = strstr("one#two\x00three", "#");
// PHP 4.2.x:  $string contains "#two"
// PHP 4.3.0:  $string contains "#two\x00three"

If you're trying to match nulls, you will probably get back an empty string:

$string = strstr("one#two\x00three", "\x00");
// PHP 4.2.x:  $string contains ""
// PHP 4.3.0:  $string contains "\x00three"
joaobett at oninet dot pt
22-Jan-2003 08:07
[Editor's Note: It's better to:

  substr($stringA, 0, strpos($stringA, $toFind)+1)

than to reverse the string twice (slow).]

//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";    $toFind = "@";

echo strrev( strchr(strrev($stringA),$toFind) );

//output: user@
mario at comicide dot com
29-Dec-2002 10:58
If you would like to count files on a directory, this might be helpful.  In this case I wanted to create a random image generator, but not have to keep track of the image count. Example: I have 4 images, and choose a random number between 1-4.  If I decide to add a 5th and 6th image, I would have to generate at random 1-6. STRSTR can help you keep track of the amount of images, without you having to update the code.

NOTE, this example is based on the naming convention

image1.gif
image2.gif
image3.gif
""""""""4"""
etc....

If you are not using it, then just make the adjustments.
------------------------------------------------------
//First a function. $path is where you want to count files
//$filter is the criteria. Ex. File names with "image" in it.

function countfiles($path, $filter)
{

$dir = opendir($path);

while ($file = readdir($dir)){

     if(strstr($file, $filter)){ $i++; }
}//end while

closedir($dir);

return $i;

}
//-------------------------------------------------

$max = countfiles("/you directory", "image");
$num = rand(1,$max);
$image = "image";
$image.= $num;
$image.= ".gif";  // or jpg, png, etc

echo "<img scr=\"$image\">";
nin at screamingslaves dot com
28-Dec-2002 12:54
Since I managed to do this in a few seconds, why not let it out to someone in the same need ...

Based on the above idea, since I had:

$string = "Some text (some note) some other text";

And say you just wanted whats *between* the parentheses (or between basically anything):

<?

function remover($string, $sep1, $sep2)
{
      
$string = substr($string, 0, strpos($string,$sep2));
      
$string = substr(strstr($string, $sep1), 1);

       return
$string;
}

$string = "Some text (some note) some other text";
$str1 = "(";
$str2 = ")";

echo
remover($string, $str1, $str2);

?>
fred at debilitron dot com
08-Nov-2002 05:44
The same thing as above, but a bit shorter, with strpos() :

$string = "email@domain.net";

$separat = "@";
$string = substr($string, 0, strpos($string,$separat));
duke as mastre dot com
15-Oct-2002 10:11
strstr(), strchr(), strrchr() _and_ stristr() are _all_ broken as of 4.2.3:

$haystack = 'John Doe <john@doe.com>';
$needle_broken = '<';
$needle_ok = '@';

echo('haystack: ' . htmlspecialchars($haystack) . '<br />');
echo('strstr using needle_broken: ' . strstr($haystack, $needle_broken) . '<br />');
echo('strstr using needle_ok: ' . strstr($haystack, $needle_ok) . '<br />');

output:
broken:
ok: @doe.com>

only function that works properly with this caracter (also '>' and possibly others) is strpos()
arni at linux dot is
23-Nov-2000 10:00
This functions is also widely used for checking if a string is in a string since it returns false if the string was not found in container.

$string = "PHP";
$container = "I love writing PHP code.";

if(strstr($container,$string)) {
     echo "found it.";
} else {
     echo "not found.";
}

<strspnstrtok>
 Last updated: Tue, 15 Nov 2005