Simplified version of Tecbrat's alternative:
<?php
$result = reset(explode($needle, $haystack));
?>
strstr
(PHP 4, PHP 5)
strstr — 文字列が最初に現れる位置を見つける
説明
haystack の中で needle が最初に現れる場所から文字列の終わりまでを返します。
注意: この関数は大文字小文字を区別することに注意してください。 大文字小文字を区別しない検索を行う場合は、stristr() を使用してください。
注意: もし特定の haystack に needle があるかどうかを調べるだけの場合、 より高速でメモリ消費も少ない strpos() を代わりに使用してください。
パラメータ
- haystack
-
入力文字列。
- needle
-
needle が文字列でない場合は、 それを整数に変換し、その番号に対応する文字として扱います。
- before_needle
-
TRUE にすると (デフォルトは FALSE です)、strstr() の返り値は、haystack の中で最初に needle があらわれる箇所より前の部分となります。
返り値
部分文字列を返します。 needle が見つからない場合は FALSE を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.3.0 | オプションの before_needle パラメータが追加されました。 |
| 4.3.0 | strstr() がバイナリセーフとなりました。 |
例
例1 strstr() の例
<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // @example.com と表示します
$user = strstr($email, '@', true); // PHP 5.3.0 以降
echo $user; // name と表示します
?>
strstr
Michael F.
11-Jun-2008 04:29
11-Jun-2008 04:29
Tecbrat
06-Feb-2008 05:52
06-Feb-2008 05:52
I was looking for an alternative to this:
<?
list($result,$null) = explode($needle,$haystack);
unset($null);
?>
But it looks like this might be the simplest work around for users of versions less than 6.
(I haven't tested this exact syntax, but it is was used like this:
<?
list($result,$null) = explode(';',$variable);
unset($null);?>
)
tim
26-Nov-2007 09:42
26-Nov-2007 09:42
I simplified prafe at prafesplace dot com's function:
<?php
function strstrbi($haystack, $needle, $before_needle=FALSE, $include_needle=TRUE, $case_sensitive=FALSE) {
//Find the position of $needle
if($case_sensitive) {
$pos=strpos($haystack,$needle);
} else {
$pos=strpos(strtolower($haystack),strtolower($needle));
}
//If $needle not found, abort
if($pos===FALSE) return FALSE;
//Adjust $pos to include/exclude the needle
if($before_needle==$include_needle) $pos+=strlen($needle);
//get everything from 0 to $pos?
if($before_needle) return substr($haystack,0,$pos);
//otherwise, go from $pos to end
return substr($haystack,$pos);
}
?>
It's now 600 bytes, down from 2k.
Also, here are replacements for strstr and stristr:
<?php
function strstr($haystack, $needle, $before_needle=FALSE) {
//Find position of $needle or abort
if(($pos=strpos($haystack,$needle))===FALSE) return FALSE;
if($before_needle) return substr($haystack,0,$pos+strlen($needle));
else return substr($haystack,$pos);
}
function stristr($haystack, $needle, $before_needle=FALSE) {
//Find position of $needle or abort
if(($pos=strpos(strtolower($haystack),strtolower($needle)))===FALSE) return FALSE;
if($before_needle) return substr($haystack,0,$pos+strlen($needle));
else return substr($haystack,$pos);
}
?>
brett dot jr dot alton at gmail dot com
26-Nov-2007 01:02
26-Nov-2007 01:02
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:
<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
prafe at prafesplace dot com
22-Nov-2007 02:14
22-Nov-2007 02:14
If you want to use the $before_needle parameter that's only in PHP 5.3.0, I found a way to use it in lower versions.
The code is a bit hefty, but it works. It also has added $include_needle and $case_sensitive.
<?php
// ==== I don't guarantee this is faster than the PHP 6 before needle, ====
// ==== but it works for PHP below 6 atleast. ====
// ==== IT ALSO HAS INCLUDE NEEDLE BOOLEAN.. ====
function strstrbi($haystack,$needle,$before_needle,
$include_needle,$case_sensitive)
{
$strstr = ($case_sensitive) ? 'strstr' : 'stristr';
if($before_needle!=true && $before_needle!=false &&
isset($before_needle)){
die('PHP: Error in function '.chr(39).'$strstrbi'.
chr(39).'
: parameter '.
chr(39).'$before_needle'.chr(39).' is
not a supplied as a boolean.');
} // END BOOLEAN CHECK '$before_needle'
if($include_needle!=true && $include_needle!=false &&
isset($include_needle)){
die('PHP: Error in function '.chr(39).'$strstrbi'.
chr(39).' : parameter '.
chr(39).'$include_needle'.chr(39).
' is not a supplied as a boolean.');
} // END BOOLEAN CHECK '$include_needle'
if($case_sensitive!=true && $case_sensitive!=false &&
isset($case_sensitive)){
die('PHP: Error in function '.chr(39).'$strstrbi'
.chr(39).' : parameter '.
chr(39).'$case_sensitive'.chr(39).'
is not a supplied as a boolean.');
} // END BOOLEAN CHECK '$case_sensitive'
if(!isset($before_needle))
{
$before_needle=false;
}
if(!isset($include_needle))
{
$include_needle=true;
}
if(!isset($case_sensitive))
{
$case_sensitive=false;
}
switch($before_needle)
{
case true:
switch($include_needle)
{
case true:
$temp=strrev($haystack);
$ret=strrev(substr($strstr($temp,$needle),0));
break;
// END case true : $include_needle
case false:
$temp=strrev($haystack);
$ret=strrev(substr($strstr($temp,$needle),1));
break;
// END case false : $include_needle
}
break;
// END case true : $before_needle
case false:
switch($include_needle)
{
case true:
$ret=$strstr($haystack,$needle);
break;
// END case true: $include_needle
case false:
$ret=substr($strstr($haystack,$needle),1);
break;
// END case false: $include_needle
}
break;
// END case false : $before_needle
}
if(!empty($ret)){
return $ret;
}else{
return false;
}
}
// === END FUNCTION 'strstrbi'
// Example
$email = 'user@example.com';
$domain = strstrbi($email, '@', false, false, false);
echo $domain; // prints example.com
$user = strstrbi($email, '@', true, false, false);
echo $user; // prints user
?>
root at mantoru dot de
10-Nov-2007 08:22
10-Nov-2007 08:22
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.
<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
$strpos = ($case_insensitive) ? 'stripos' : 'strpos';
$pos = $strpos($haystack, $needle);
if (is_int($pos)) {
return substr($haystack, $pos + strlen($needle));
}
// Most likely false or null
return $pos;
}
// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo $domain; // prints example.com
?>
fire.minded.design at gmail dot com
25-Sep-2007 08:06
25-Sep-2007 08:06
for eamon:
preg_replace is wonderful for that sort of thing, amongst so much else.
<?php
$string = "a string with!0o|u7t stuf34-f2~ in#4 in it";
// No numbers
$string = preg_replace("![0-9]!", "", $string);
// $string is now "a string with!o|ut stuf-f~ in# in it"
// Nothing but alphabetic
$string = preg_replace("![^0-9A-Za-z\s]!", "", $string);
// $string is now "a string without stuff in in it"
?>
Christian Dywan
30-Jun-2007 11:25
30-Jun-2007 11:25
@Eric:
Please do not test for the occurence of a substring with strstr. As you should already have read above, strpos is much faster for this.
Eric
16-Jun-2007 09:26
16-Jun-2007 09:26
Example 1. stristr() example
<?php
$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e');
// outputs ER@EXAMPLE.com
?>
Example 2. Testing if a string is found or not
<?php
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
Example 3. Using a non "string" needle
<?php
$string = 'APPLE';
echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>
I use this a lot at http://www.linksback.org
gigaman2003 at halfempty dot co dot uk
25-Feb-2007 05:48
25-Feb-2007 05:48
Often you will need to find all occurrences of a string (for security escapes and such)
So I wrote this function to return an array with the locations of all the occurrences. Almost like an advanced strstr.
function findall($needle, $haystack)
{
//Setting up
$buffer=''; //We will use a 'frameshift' buffer for this search
$pos=0; //Pointer
$end = strlen($haystack); //The end of the string
$getchar=''; //The next character in the string
$needlelen=strlen($needle); //The length of the needle to find (speeds up searching)
$found = array(); //The array we will store results in
while($pos<$end)//Scan file
{
$getchar = substr($haystack,$pos,1); //Grab next character from pointer
if($getchar!="\n" || buffer<$needlelen) //If we fetched a line break, or the buffer is still smaller than the needle, ignore and grab next character
{
$buffer = $buffer . $getchar; //Build frameshift buffer
if(strlen($buffer)>$needlelen) //If the buffer is longer than the needle
{
$buffer = substr($buffer,-$needlelen);//Truncunate backwards to needle length (backwards so that the frame 'moves')
}
if($buffer==$needle) //If the buffer matches the needle
{
$found[]=$pos-$needlelen+1; //Add the location of the needle to the array. Adding one fixes the offset.
}
}
$pos++; //Increment the pointer
}
if(array_key_exists(0,$found)) //Check for an empty array
{
return $found; //Return the array of located positions
}
else
{
return false; //Or if no instances were found return false
}
}
Haven't had the chance to speed test it, but many optimizations should be possible. It just works enough for me. Hope it saves someone a lot of time.
eamon at gizzle dot co dot uk
30-Jan-2007 06:21
30-Jan-2007 06:21
After some interesting projects that required the use of requiring only the chars of any given string i thought i'll just put it up. Simple code.
<?php
function strchrs($str)
{
$n = strlen($str);
$w = "";
for($i = 0; $i < $n; $i ++)
{
if(!is_numeric($str[$i]))
$w .= $str[$i];
}
return $w;
}
?>
Hey I'm building a new DB & Datasource abstraction layer, the framework's been built does anyone wannt help out. I need someone with a SYBASE database, and I'm also working on some new ways of dealing with XML contact me as I don't have much time to complete it. It's actually 3x faster than MDB2, and because it doesn't require PEAR its easier to install. Only OOP developers plz.
always_sleepz0r at removethisyahoo dot co dot uk
15-Jan-2006 04:38
15-Jan-2006 04: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
16-Nov-2005 09:20
16-Nov-2005 09: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
07-Jun-2005 01: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ör att klippa av en sträng som innehåller skandinaviska (eller Franska, för den delen) tecken, kan man göra såhä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ör att klippa av en sträng som inneh&ar
With the decode-encode snippet:
För att klippa av en sträng som innehåller skandin
First post in this db ;)
Best regards, Mikael Rnn, FIN
leo dot nard at free dot fr
24-May-2005 06:12
24-May-2005 06: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: "à&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
23-Apr-2005 04:55
23-Apr-2005 04: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
19-Mar-2005 10:07
19-Mar-2005 10: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
09-Feb-2005 12:54
09-Feb-2005 12: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
04-Sep-2004 12:55
04-Sep-2004 12: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)
23-Apr-2004 01:02
23-Apr-2004 01: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 07:22
01-Apr-2004 07: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 11:16
23-Feb-2004 11: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
22-Jan-2004 05:25
22-Jan-2004 05: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 08:08
14-Mar-2003 08: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 09:02
07-Mar-2003 09: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
php at silisoftware dot com
15-Feb-2003 08:37
15-Feb-2003 08: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"
