|
|
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; ?>
|
|
Замечание:
Если нужно лишь определить, встречается ли подстрока
needle в haystack,
используйте функцию strpos(), которая работает
быстрее и потребляет меньше памяти.
С версии PHP 4.3.0 strstr() безопасна для
обработки данных в двоичной форме.
См. также описание функций
ereg(),
preg_match(),
stristr(),
strpos(),
strrchr() и
substr().
fire.minded.design at gmail dot com
24-Sep-2007 04: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";
$string = preg_replace("![0-9]!", "", $string);
$string = preg_replace("![^0-9A-Za-z\s]!", "", $string);
?>
Christian Dywan
29-Jun-2007 07: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
15-Jun-2007 05:26
Example 1. stristr() example
<?php
$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e');
?>
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';
}
?>
Example 3. Using a non "string" needle
<?php
$string = 'APPLE';
echo stristr($string, 97); ?>
I use this a lot at http://www.linksback.org
gigaman2003 at halfempty dot co dot uk
24-Feb-2007 12: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
29-Jan-2007 01: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
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ö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;
$newstr = htmlentities(substr(html_entity_decode($oldstr), 0, $length));
$newstr2 = substr($oldstr, 0, $length);
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 R
|
|