php 获取php 去除特定字符符

php 截取指定字符之前的字符串_百度知道
php 截取指定字符之前的字符串
.如:$a=&id=1&name=awen$pwd=123456& 我想要将变量$a
值中最后一个&符号以及后面的参数去掉 ,得到一个新值;id=1&name=awen$pwd=123456&pic=5&$a = &quot
$a值的长度 ,以及参数个数都是未定的 ..
要去除掉最后一个&符号以及后面所带的参数
我有更好的答案
0,即用以下表达式即可获得新的a值;));
$newa = substr($a,strrpos($a,'&&#39可以结合substr函数及strrpos函数使用
采纳率:53%
应该可以用lasindexof()和substring()这个方法实现吧。我没有用过php,不知道可不可以实现。你试一下吧
把数据从后向前截取吧
为您推荐:
其他类似问题
您可能关注的内容
字符串的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。PHP怎么从网页中获取某一指定的字符串
[问题点数:20分,结帖人van416521]
PHP怎么从网页中获取某一指定的字符串
[问题点数:20分,结帖人van416521]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
2013年6月 Linux/Unix社区大版内专家分月排行榜第二2013年5月 Linux/Unix社区大版内专家分月排行榜第二2013年3月 Linux/Unix社区大版内专家分月排行榜第二2013年1月 Linux/Unix社区大版内专家分月排行榜第二2012年12月 Linux/Unix社区大版内专家分月排行榜第二2012年8月 Linux/Unix社区大版内专家分月排行榜第二2011年12月 Linux/Unix社区大版内专家分月排行榜第二2011年10月 C/C++大版内专家分月排行榜第二2011年10月 Linux/Unix社区大版内专家分月排行榜第二
2012年6月 C/C++大版内专家分月排行榜第三2012年6月 PHP大版内专家分月排行榜第三2012年5月 C/C++大版内专家分月排行榜第三2012年3月 Linux/Unix社区大版内专家分月排行榜第三2012年2月 Linux/Unix社区大版内专家分月排行榜第三2011年11月 C/C++大版内专家分月排行榜第三
2013年6月 Linux/Unix社区大版内专家分月排行榜第二2013年5月 Linux/Unix社区大版内专家分月排行榜第二2013年3月 Linux/Unix社区大版内专家分月排行榜第二2013年1月 Linux/Unix社区大版内专家分月排行榜第二2012年12月 Linux/Unix社区大版内专家分月排行榜第二2012年8月 Linux/Unix社区大版内专家分月排行榜第二2011年12月 Linux/Unix社区大版内专家分月排行榜第二2011年10月 C/C++大版内专家分月排行榜第二2011年10月 Linux/Unix社区大版内专家分月排行榜第二
2012年6月 C/C++大版内专家分月排行榜第三2012年6月 PHP大版内专家分月排行榜第三2012年5月 C/C++大版内专家分月排行榜第三2012年3月 Linux/Unix社区大版内专家分月排行榜第三2012年2月 Linux/Unix社区大版内专家分月排行榜第三2011年11月 C/C++大版内专家分月排行榜第三
2012年3月 PHP大版内专家分月排行榜第三
2010年3月 PHP大版内专家分月排行榜第三2005年4月 PHP大版内专家分月排行榜第三
匿名用户不能发表回复!|php正则提取字符串中的数字
时间: 15:48
来源:未知 | 作者:我爱学习网
| 本文已影响
分享两个非常好用的正则提取字符串中数字的方法
1、提取首次出现的连续的数字方法:
$str='http://www.5ixuexiwang.com/phprumenjiaocheng/75.html';
if (preg_match('|(\d+)|',$str,$r)) echo $r[1];
2、提取字符串中所有数字
echo preg_replace('/\D/s', '', $str);
3、提取字符串中所有数字放入数组
$ex1 = &/\d+/&;
preg_match_all($ex1,$str,$arr1);
print_r($arr1);
//执行结果:Array ( [0] =& Array ( [0] =& 5 [1] =& 2017 [2] =& 0322 [3] =& 2175 ) )
$ex2 = &/\d/&;
preg_match_all($ex2,$str,$arr2);
print_r($arr2);
//执行结果:Array ( [0] =& Array ( [0] =& 5 [1] =& 2 [2] =& 0 [3] =& 1 [4] =& 7 [5] =& 0 [6] =& 3 [7] =& 2 [8] =& 2 [9] =& 2 [10] =& 1 [11] =& 7 [12] =& 5 ) )
(责任编辑:我爱学习网)
我爱学习网精心筛选编辑,将最精华的学习资料奉献给大家!
记忆力学习
教你如何高效背单词
脑龄测试题,测测你的脑龄是多少
IQ智商大挑战(FLASH)
php导出内容到txt并自动弹出下载文件...
Tipask问答系统模板二次开发时,当我们要在问题列表中显示问题所属用户的头像时,可以...PHP 查找字符串首次出现的位置
在线手册:&
strpos & 查找字符串首次出现的位置
int strpos
( string $haystack
[, int $offset = 0
在该字符串中进行查找。
如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。
可选的 offset 参数可以用来指定从 haystack 中的哪一个字符开始查找。返回的数字位置是相对于 haystack 的起始位置而言的。
以整型返回位置信息。如果没找到 needle, strpos() 将返回布尔型的 FALSE 值。
Warning此函数可能返回布尔值
FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 章节以获取更多信息。应使用
来测试此函数的返回值。
Example #1 使用 ===
&?php$mystring&=&'abc';$findme&&&=&'a';$pos&=&strpos($mystring,&$findme);//&注意这里使用的是&===。简单的&==&不能像我们期待的那样工作,//&因为&'a'&是第&0&位置上的(第一个)字符。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 使用 !==
&?php$mystring&=&'abc';$findme&&&=&'a';$pos&=&strpos($mystring,&$findme);//&使用&!==&操作符。使用&!=&不能像我们期待的那样工作,//&因为&'a'&的位置是&0。语句&(0&!=&false)&的结果是&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 使用位置偏移量
&?php//&忽视位置偏移量之前的字符进行查找$newstring&=&'abcdef&abcdef';$pos&=&strpos($newstring,&'a',&1);&//&$pos&=&7,&不是&0?&
Note: 此函数可安全用于二进制对象。
- 计算指定字符串在目标字符串中最后一次出现的位置
- 查找字符串首次出现的位置(不区分大小写)
- 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
- 查找指定字符在字符串中的最后一次出现
- 返回字符串的子串
- strstr 函数的忽略大小写版本
- 查找字符串的首次出现
在线手册:&
The most straightforward way to prevent this function from returning 0 is:
strpos('x'.$haystack, $needle, 1)
The 'x' is simply a garbage character which is only there to move everything 1 position.
The number 1 is there to make sure that this 'x' is ignored in the search.
This way, if $haystack starts with $needle, then the function returns 1 (rather than 0).
Just&a&quick&note,&if&by&some&chance&you&pass&an&array&to&strpos&function&you&might&have&unexpected&behaviour.&?php$foobar&=&array();if(strpos($foobar,&'something')&!==&false)&{}?&The&above&condition&will&actually&pass&and&execute&your&code.
There&is&a&more&efficient&way&when&looking&for&the&position&of&each&occurrence:&
&?php
while($count&=&strpos($input1,&$input2,&$count+1))
&&&&$output[]&=&$count+1;
?&
Use&the&offset&value,&then&you&don't&spend&a&ton&of&time&re-writing&the&value&into&memory
when you want to know how much of substring occurrences, you'll use &substr_count&.
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :
function strpos_r($haystack, $needle)
if(strlen($needle) & strlen($haystack))
trigger_error(sprintf(&%s: length of argument 2 must be &= argument 1&, __FUNCTION__), E_USER_WARNING);
$seeks = array();
while($seek = strrpos($haystack, $needle))
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
it will return an array of all occurrences a the substring in the string
$test = &this is a test for testing a test function... blah blah&;
var_dump(strpos_r($test, &test&));
array(3) {
Paul-antoine
Malézieux.
This&is&a&function&I&wrote&to&find&all&occurrences&of&a&string,&using&strpos&recursively.&?phpfunction&strpos_recursive($haystack,&$needle,&$offset&=&0,&&$results&=&array())&{&&&&&&&&&&&&&&&&&&&&$offset&=&strpos($haystack,&$needle,&$offset);&&&&if($offset&===&false)&{&&&&&&&&return&$results;&&&&&&&&&&&&&&&&}&else&{&&&&&&&&$results[]&=&$offset;&&&&&&&&return&strpos_recursive($haystack,&$needle,&($offset&+&1),&$results);&&&&}}?&This&is&how&you&use&it:&?php$string&=&'This&is&some&string';$search&=&'a';$found&=&strpos_recursive($string,&$search);if($found)&{&&&&foreach($found&as&$pos)&{&&&&&&&&echo&'Found&"'.$search.'"&in&string&"'.$string.'"&at&position&&b&'.$pos.'&/b&&br&/&';&&&&}&&&&}&else&{&&&&echo&'"'.$search.'"&not&found&in&"'.$string.'"';}?&
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that
strpos() !== false
is a different beast then:
strpos() === true
since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
A&pair&of&functions&to&replace&every&nth&occurrence&of&a&string&with&another&string,&starting&at&any&position&in&the&haystack.&The&first&works&on&a&string&and&the&second&works&on&a&single-level&array&of&strings,&treating&it&as&a&single&string&for&replacement&purposes&(any&needles&split&over&two&array&elements&are&ignored).Can&be&used&for&formatting&dynamically-generated&HTML&output&without&touching&the&original&generator:&e.g.&add&a&newLine&class&tag&to&every&third&item&in&a&floated&list,&starting&with&the&fourth&item.&&?php/*&String&Replace&at&Intervals&&&by&Glenn&Herbert&(gjh42)&&&&&*/&//(basic&locator&by&someone&else&-&name&unknown)//strnposr()&-&Find&the&position&of&nth&needle&in&haystack.function&strnposr($haystack,&$needle,&$occurrence,&$pos&=&0)&{&&&&return&($occurrence&2)?strpos($haystack,&$needle,&$pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack,&$needle,&$pos)&+&1);}//gjh42//replace&every&nth&occurrence&of&$needle&with&$repl,&starting&from&any&positionfunction&str_replace_int($needle,&$repl,&$haystack,&$interval,&$first=1,&$pos=0)&{&&if&($pos&&=&strlen($haystack)&or&substr_count($haystack,&$needle,&$pos)&&&$first)&return&$haystack;&&$firstpos&=&strnposr($haystack,&$needle,&$first,&$pos);&&$nl&=&strlen($needle);&&$qty&=&floor(substr_count($haystack,&$needle,&$firstpos&+&1)/$interval);&&do&{&//in&reverse&order&&&&$nextpos&=&strnposr($haystack,&$needle,&($qty&*&$interval)&+&1,&$firstpos);&&&&&$qty--;&&&&$haystack&=&substr_replace($haystack,&$repl,&$nextpos,&$nl);&&}&while&($nextpos&&&$firstpos);&&return&$haystack;}&&//$needle&=&string&to&find&&//$repl&=&string&to&replace&needle&&//$haystack&=&string&to&do&replacing&in&&//$interval&=&number&of&needles&in&loop&&//$first=1&=&first&occurrence&of&needle&to&replace&(defaults&to&first)&&&//$pos=0&=&position&in&haystack&string&to&start&from&(defaults&to&first)&&//replace&every&nth&occurrence&of&$needle&with&$repl,&starting&from&any&position,&in&a&single-level&arrayfunction&arr_replace_int($needle,&$repl,&$arr,&$interval,&$first=1,&$pos=0,&$glue='|+|')&{&&if&(!is_array($arr))&&return&$arr;&&foreach($arr&as&$key=&$value){&&&&if&(is_array($arr[$key]))&return&$arr;&&}&&$haystack&=&implode($glue,&$arr);&&$haystack&=&str_replace_int($needle,&$repl,&$haystack,&$interval,&$first,&$pos);&&$tarr&=&explode($glue,&$haystack);&&$i&=&0;&&foreach($arr&as&$key=&$value){&&&&$arr[$key]&=&$tarr[$i];&&&&$i++;&&}&&return&$arr;}?&If&$arr&is&not&an&array,&or&a&multilevel&array,&it&is&returned&unchanged.
When&using&GLOB_BRACE&to&find&files&on&a&local&computer,&note&that&including&the&drive&lettername&within&the&braces&may&cause&the&behavior&to&not&work&as&expected:&?php$location&=&"{c:/foo/*.txt,c:/foo/bar/*.txt}";&//&&&will&NOT&work$location&=&"c:{/foo/*.txt,/foo/bar/*.txt}";&//&&&works$location&=&"c:/{foo/*.txt,foo/bar/*.txt}";&//&&&works$location&=&"{/foo/*.txt,/foo/bar/*.txt}";&//&&&worksprint_r(glob($location,&GLOB_BRACE));?&
strpos&that&accepts&an&array&for&$needle&?php//&strpos&that&takes&an&array&of&values&to&match&against&a&string//&note&the&stupid&argument&order&(to&match&strpos)function&strpos_arr($haystack,&$needle)&{&&&&if(!is_array($needle))&$needle&=&array($needle);&&&&foreach($needle&as&$what)&{&&&&&&&&if(($pos&=&strpos($haystack,&$what))!==false)&return&$pos;&&&&}&&&&return&false;}?&----------------------------http://www.show-ip.org
A&simple&way&to&get&the&FIRST&occurence&of&any&$needle.Needed&if&more&than&one&$needle&could&occur&in&$haystack&and&you&want&the&first&occurence&of&any&$needle.&?phpfunction&strpos_arr($haystack,&$needle)&{&&&&$First&=&strlen($haystack);&&&&if(!is_array($needle))&$needle&=&array($needle);&&&&foreach($needle&as&$what)&{&&&&&&&&$pos&=&strpos($haystack,&$what);&&&&&&&&if($pos&!==&false)&&&&&&&&{&&&&&&&&&&&&if($pos&&&$First)&$First&=&$pos;&&&&&&&&}&&&&}&&&&return&$First&==&strlen($haystack)&?&false&:&$First;}?&
My&version&of&strpos&with&needles&as&an&array.&Also&allows&for&a&string,&or&an&array&inside&an&array.&?phpfunction&strpos_array($haystack,&$needles)&{&&&&if&(&is_array($needles)&)&{&&&&&&&&foreach&($needles&as&$str)&{&&&&&&&&&&&&if&(&is_array($str)&)&{&&&&&&&&&&&&&&&&$pos&=&strpos_array($haystack,&$str);&&&&&&&&&&&&}&else&{&&&&&&&&&&&&&&&&$pos&=&strpos($haystack,&$str);&&&&&&&&&&&&}&&&&&&&&&&&&if&($pos&!==&FALSE)&{&&&&&&&&&&&&&&&&return&$pos;&&&&&&&&&&&&}&&&&&&&&}&&&&}&else&{&&&&&&&&return&strpos($haystack,&$needles);&&&&}}//&Testecho&strpos_array('This&is&a&test',&array('test',&'drive'));&//&Output&is&10?&
A&complete&set&of&strn*pos&functions&that&look&for&the&nth&occurrence&of&the&needle&in&the&haystack.&I&prefer&this&implementation&of&strnpos&because&it&doesn't&give&visible&warnings&when&supplied&with&a&needle&of&length&0&(which&is,&admittedly,&non-standard&behavior).&&Based&on&a&version&I&[originally&posted&on&05-MAR-2010];&this&new&version&conforms&more&to&the&semantics&of&strpos.
/**
&*&&This&function&implements&all&the&strn*pos&functions,&which&return&the&$nth&occurrence&of&$needle
&*&&in&$haystack,&or&false&if&it&doesn't&exist&/&when&illegal&parameters&have&been&supplied.
&*
&*&&@param&&string&&$haystack&&&&&&&the&string&to&search&in.
&*&&@param&&MIXED&&&$needle&&&&&&&&&the&string&or&the&ASCII&value&of&the&character&to&search&for.
&*&&@param&&integer&$nth&&&&&&&&&&&&the&number&of&the&occurrence&to&look&for.
&*&&@param&&integer&$offset&&&&&&&&&the&position&in&$haystack&to&start&looking&for&$needle.
&*&&@param&&bool&&&&$insensitive&&&&should&the&function&be&case&insensitive?
&*&&@param&&bool&&&&$reverse&&&&&&&&should&the&function&work&its&way&backwards&in&the&haystack?
&*&&@return&MIXED&&&integer&&&&&&&&&either&the&position&of&the&$nth&occurrence&of&$needle&in&$haystack,
&*&&&&&&&&&&&&&&&or&boolean&&&&&&&&&false&if&it&can't&be&found.
&*/
function&strnripos_generic(&$haystack,&$needle,&$nth,&$offset,&$insensitive,&$reverse&)
{
&&&&//&&If&needle&is&not&a&string,&it&is&converted&to&an&integer&and&applied&as&the&ordinal&value&of&a&character.
&&&&if(&!&is_string(&$needle&)&)&{
&&&&&&&&$needle&=&chr(&(int)&$needle&);
&&&&}
&&&&//&&Are&the&supplied&values&valid&/&reasonable?
&&&&$len&=&strlen(&$needle&);
&&&&if(&1&&&$nth&||&0&===&$len&)&{
&&&&&&&&return&false;
&&&&}
&&&&if(&$insensitive&)&{
&&&&&&&&$haystack&=&strtolower(&$haystack&);
&&&&&&&&$needle&&&=&strtolower(&$needle&&&);
&&&&}
&&&&if(&$reverse&)&{
&&&&&&&&$haystack&=&strrev(&$haystack&);
&&&&&&&&$needle&&&=&strrev(&$needle&&&);
&&&&}
&&&&//&&$offset&is&incremented&in&the&call&to&strpos,&so&make&sure&that&the&first
&&&&//&&call&starts&at&the&right&position&by&initially&decreasing&$offset&by&$len.
&&&&$offset&-=&$len;
&&&&do
&&&&{
&&&&&&&&$offset&=&strpos(&$haystack,&$needle,&$offset&+&$len&);
&&&&}&while(&--$nth&&&&&false&!==&$offset&);
&&&&return&false&===&$offset&||&!&$reverse&?&$offset&:&strlen(&$haystack&)&-&$offset;
}
/**
&*&&@see&&&&strnripos_generic
&*/
function&strnpos(&$haystack,&$needle,&$nth,&$offset&=&0&)
{
&&&&return&strnripos_generic(&$haystack,&$needle,&$nth,&$offset,&false,&false&);
}
/**
&*&&@see&&&&strnripos_generic
&*/
function&strnipos(&$haystack,&$needle,&$nth,&$offset&=&0&)
{
&&&&return&strnripos_generic(&$haystack,&$needle,&$nth,&$offset,&true,&false&);
}
/**
&*&&@see&&&&strnripos_generic
&*/
function&strnrpos(&$haystack,&$needle,&$nth,&$offset&=&0&)
{
&&&&return&strnripos_generic(&$haystack,&$needle,&$nth,&$offset,&false,&true&);
}
/**
&*&&@see&&&&strnripos_generic
&*/
function&strnripos(&$haystack,&$needle,&$nth,&$offset&=&0&)
{
&&&&return&strnripos_generic(&$haystack,&$needle,&$nth,&$offset,&true,&true&);
}
$haystack&=&'Dit&is&een&HoTtentotTentenTentenToonstellingTest!';
echo&strnpos&&(&$haystack,&'t',&5&),&'&===&',&strnpos&&(&$haystack,&116,&5&),&PHP_EOL;
echo&strnipos&(&$haystack,&'t',&5&),&'&===&',&strnipos&(&$haystack,&116,&5&),&PHP_EOL;
echo&strnrpos&(&$haystack,&'t',&5&),&'&===&',&strnrpos&(&$haystack,&116,&5&),&PHP_EOL;
echo&strnripos(&$haystack,&'t',&5&),&'&===&',&strnripos(&$haystack,&116,&5&),&PHP_EOL;
echo&PHP_EOL;
echo&strnpos&&(&$haystack,&'T',&5&),&'&===&',&strnpos&&(&$haystack,&&84,&5&),&PHP_EOL;
echo&strnipos&(&$haystack,&'T',&5&),&'&===&',&strnipos&(&$haystack,&&84,&5&),&PHP_EOL;
echo&strnrpos&(&$haystack,&'T',&5&),&'&===&',&strnrpos&(&$haystack,&&84,&5&),&PHP_EOL;
echo&strnripos(&$haystack,&'T',&5&),&'&===&',&strnripos(&$haystack,&&84,&5&),&PHP_EOL;
?&
beware the mindless &if needle is not string& :
root@voice1:/www/voice_ed#php -r 'var_dump(strpos(&X));'
bool(false)
root@voice1:/www/voice_ed#php -r 'var_dump(strpos(&X1234567&,&5&));'
root@voice1:/www/voice_ed#
&?php$my_array&=&array&('100,101',&'200,201',&'300,301');$check_me_in&=&array&('100','200','300','400');foreach&($check_me_in&as&$value_cmi){&&&&$is_in=FALSE;&#asume&that&$check_me_in&isn't&in&$my_array&&&&foreach&($my_array&as&$value_my){&&&&&&&&$pos&=&strpos($value_my,&$value_cmi);&&&&&&&&if&($pos===0)&&&&&&&&&&&&$pos++;&&&&&&&&if&($pos==TRUE){&&&&&&&&&&&&$is_in=TRUE;&&&&&&&&&&&&$value_my2=$value_my;&&&&&&&&&&&&}&&&&}&&&&if&($is_in)&echo&"ID&$value_cmi&in&\$check_me_in&I&found&in&value&'$value_my2'&\n";}?&The&above&example&will&outputID&100&in&$check_me_in&I&found&in&value&'100,101'&ID&200&in&$check_me_in&I&found&in&value&'200,201'&ID&300&in&$check_me_in&I&found&in&value&'300,301'
Parse&strings&between&two&others&in&to&array.
&?php
function&g($string,$start,$end){
&&&&&preg_match_all('/'&.&preg_quote($start,&'/')&.&'(.*?)'.&preg_quote($end,&'/').'/i',&$string,&$m);
&&&&&$out&=&array();
&&&&&foreach($m[1]&as&$key&=&&$value){
&&&&&&&$type&=&explode('::',$value);
&&&&&&&if(sizeof($type)&1){
&&&&&&&&&&if(!is_array($out[$type[0]]))
&&&&&&&&&&&&&$out[$type[0]]&=&array();
&&&&&&&&&&$out[$type[0]][]&=&$type[1];
&&&&&&&}&else&{
&&&&&&&&&&$out[]&=&$value;
&&&&&&&}
&&&&&}
&&return&$out;
}
print_r(g('Sample&text,&[/text&to&extract/]&Rest&of&sample&text&[/WEB::http://google.com/]&bla&bla&bla.&','[/','/]'));
?&
results:
Array
(
&&&&[0]&=&&text&to&extract
&&&&[WEB]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[0]&=&&http://google.com
&&&&&&&&)
Can&be&helpfull&to&custom&parsing&:)
strpos&that&accepts&an&array&for&$needle&?php//&strpos&that&takes&an&array&of&values&to&match&against&a&string//&note&the&stupid&argument&order&(to&match&strpos)function&strpos_arr($haystack,&$needle)&{&&&&if(!is_array($needle))&$needle&=&array($needle);&&&&foreach($needle&as&$what)&{&&&&&&&&if(($pos&=&strpos($haystack,&$what))!==false)&return&$pos;&&&&}&&&&return&false;}?&
I&found&that&whatever&I&was&using&as&a&test&with&strpos&it&came&out&false&exept&if&$pos&was&==&1I&figured&it&gives&me&a&numeric&value&if&found&else&it&is&null&or&falsehere&is&what&i&did&to&make&my&code&work:&?php//EXAMPLE&1:$quiamime&=&',64,68,70,';$me&=&'64'$posi&=&strpos($quiaime,&",$me,");&&//posi&is&equal&to&0if&(!is_numeric($posi)){&//code&here}else{&&//else&code&here}//EXAMPLE&2:$quiamime&=&',68,70,64,';$me&=&'64'$posi&=&strpos($quiaime,&",$me,");&&//posi&is&equal&to&6if&(!is_numeric($posi)){&//code&here}else{&&//else&code&here}//EXAMPLE&3:$quiamime&=&',68,70,';$me&=&'64'$posi&=&strpos($quiaime,&",$me,");&&//posi&is&equal&to&NULL&or&FALSEif&(!is_numeric($posi)){&//code&here}else{&&//else&code&here}?&
Dan&Brown&and&I&had&a&discussion&on&the&PHP&list&about&the&speed&difference&between&the&popular&three&string&searching&techniques.&He&wrote&a&simple&timing&test,&and&I&adapted&it&further.&The&end&result&is&that&all&three&are&very&close&and&not&even&noticeable&for&sets&&&1M.&Although,&technically&strpos()&is&about&twice&as&fast&(as&the&docs&allude&to&above).&Here&it&is&for&your&own&amusement&and&testing&purposes.&?phpfor&($i&=&0;&$i&&&1000000;&$i++&)&&&&$o[]&=sprintf('%04d-%02d-%02d',rand(0000,9999),rand(00,99),rand(00,99));#print_r($o);echo&"array&of&".number_format($i)."\n";###################################################################$now&=&microtime(true);for($i=0;$i&count($o);$i++)&{&&&&&&&if(preg_match('/^[0]{4,}\-/U',$o[$i]))&{&&&&&&&&&&&&&&&//echo&"Offset&#".$i."&matches:&".$o[$i].PHP_EOL;&&&&&&&}}$rank['preg_match']&=&(microtime(true)&-&$now);###################################################################$later&=&microtime(true);for($i=0;$i&count($o);$i++)&{&&&&&&&&if(substr($o[$i],0,4)&==&"0000")&{&&&&&&&&&&&&&&&&//echo&"Offset&#".$i."&matches:&".$o[$i].PHP_EOL;&&&&&&&&}}$rank['substr']&=&(microtime(true)&-&$later);###################################################################$after&=&microtime(true);for($i=0;$i&count($o);$i++)&{&&&&&&&&if(strpos($o[$i],&'0000')&===&0)&{&&&&&&&&&&&&&&&&//echo&"Offset&#".$i."&matches:&".$o[$i].PHP_EOL;&&&&&&&&}}$rank['strpos']&=&(microtime(true)&-&$after);###################################################################asort($rank);print_r($rank);?&array&of&10,000Array(&&&&[strpos]&=&&0.17&&&&[substr]&=&&0.3&&&&[preg_match]&=&&0.6)array&of&100,000Array(&&&&[strpos]&=&&0.6&&&&[substr]&=&&0.&&&&[preg_match]&=&&0.)array&of&1,000,000Array(&&&&[strpos]&=&&0.&&&&[substr]&=&&1.&&&&[preg_match]&=&&1.)I&ran&out&of&memory&with&more&than&1M&array&elements.
A&function&I&made&to&find&the&first&occurrence&of&a&particular&needle&not&enclosed&in&quotes(single&or&double).&Works&for&simple&nesting&(no&backslashed&nesting&allowed).
&?php
function&strposq($haystack,&$needle,&$offset&=&0){
&&&&$len&=&strlen($haystack);
&&&&$charlen&=&strlen($needle);
&&&&$flag1&=&false;
&&&&$flag2&=&false;
&&&&for($i&=&$offset;&$i&&&$len;&$i++){
&&&&&&&&if(substr($haystack,&$i,&1)&==&"'"){
&&&&&&&&&&&&$flag1&=&!$flag1&&&&!$flag2&?&true&:&false;
&&&&&&&&}
&&&&&&&&if(substr($haystack,&$i,&1)&==&'"'){
&&&&&&&&&&&&$flag2&=&!$flag1&&&&!$flag2&?&true&:&false;
&&&&&&&&}
&&&&&&&&if(substr($haystack,&$i,&$charlen)&==&$needle&&&&!$flag1&&&&!$flag2){
&&&&&&&&&&&&return&$i;&&&&&&&&
&&&&&&&&}
&&&&}
&&&&return&false;
}
echo&strposq("he'llo'\"'som\"e;crap",&";");&//16
?&
This&function&finds&postion&of&nth&occurence&of&a&letter&starting&from&offset.&?phpfunction&nth_position($str,&$letter,&$n,&$offset&=&0){&&&&$str_arr&=&str_split($str);&&&&$letter_size&=&array_count_values(str_split(substr($str,&$offset)));&&&&if(&!isset($letter_size[$letter])){&&&&&&&&trigger_error('letter&"'&.&$letter&.&'"&does&not&exist&in&'&.&$str&.&'&after&'&.&$offset&.&'.&position',&E_USER_WARNING);&&&&&&&&return&false;&&&&}&else&if($letter_size[$letter]&&&$n)&{&&&&&&&&trigger_error('letter&"'&.&$letter&.&'"&does&not&exist&'&.&$n&.'&times&in&'&.&$str&.&'&after&'&.&$offset&.&'.&position',&E_USER_WARNING);&&&&&&&&return&false;&&&&}&&&&for($i&=&$offset,&$x&=&0,&$count&=&(count($str_arr)&-&$offset);&$i&&&$count,&$x&!=&$n;&$i++){&&&&&&&&if($str_arr[$i]&==&$letter){&&&&&&&&&&&&$x++;&&&&&&&&}&&&&}&&&&return&$i&-&1;}echo&nth_position('foobarbaz',&'a',&2);&//7echo&nth_position('foobarbaz',&'b',&1,&4);&//6?&
This functions throws an &Offset not contained in string& error if the offset is not in between 0 and the length of string.
The&following&function&use&to&redirect&to&URL&correctly&if&the&URL&have&"http://"&or&"https://",&or&to&relative&URL&on&your&site.
&?php
function&forward($url&=&NULL){
&&&&$root&=&"http://example.com/mydir/";
&&&&
&&&&if($url&==&NULL)&//&Go&to&homepage
&&&&&&&&$url&=&$root;
&&&&else&{
&&&&&&&&$pos&=&strpos($url,&"http://");
&&&&&&&&if&($pos&===&false)&
&&&&&&&&&&&&$pos&=&strpos($url,&"https://");
&&&&&&&&
&&&&&&&&if&($pos&===&false&||&$pos&&&0)&//&Go&to&relative&URL&on&your&site
&&&&&&&&&&&&$url&=&$root&.&$url;
&&&&}
&&&&
&&&&header('Location:'.$url);&&&&
}
?&
Function&to&get&the&string&pos&($search),&before&the&position&($pos)&passed&as&parameter.&?phpfunction&strposReverse(&$str,&$search,&$pos&){&&&&&&&&$str&=&strrev($str);&&&&&&&&$search&=&strrev($search);&&&&&&&&$pos&=&(strlen($str)&-&1)&-&$pos;&&&&&&&&&&&&&&&&$posRev&=&strpos(&$str,&$search,&$pos&);&&&&&&&&return&(strlen($str)&-&1)&-&$posRev&-&(strlen($search)&-&1);&&&&}?&
A&strpos&modification&to&return&an&array&of&all&the&positions&of&a&needle&in&the&haystack&
&?php
function&strallpos($haystack,$needle,$offset&=&0){
&&&&$result&=&array();
&&&&for($i&=&$offset;&$i&strlen($haystack);&$i++){
&&&&&&&&$pos&=&strpos($haystack,$needle,$i);
&&&&&&&&if($pos&!==&FALSE){
&&&&&&&&&&&&$offset&=&&$pos;
&&&&&&&&&&&&if($offset&&=&$i){
&&&&&&&&&&&&&&&&$i&=&$offset;
&&&&&&&&&&&&&&&&$result[]&=&$offset;
&&&&&&&&&&&&}
&&&&&&&&}
&&&&}
&&&&return&$result;
}
?&
&?php
$haystack&=&"ASD&is&trying&to&get&out&of&the&ASDs&cube&but&the&other&ASDs&told&him&that&his&behavior&will&destroy&the&ASDs&world";
$needle&=&"ASD";
print_r(strallpos($haystack,$needle));
//getting&all&the&positions&starting&from&a&specified&position
print_r(strallpos($haystack,$needle,34));
?&
I found in a certain bit of my code that under certain circumstances, $needle could be an empty string. This caused strpos to generate an error message.
To get round it, I had to first test to see if $needle was an empty string, and then (ie 'else') go forward and do the strpos test if not.
This&function&find&position&of&first&occurrence&of&any&$needles&in&a&string&$haystack.
Return&the&position&as&an&integer.&If&needles&is&not&found,&strposa()&will&return&boolean&&FALSE.&
&?php
function&strposa($haystack&,$needles=array(),$offset=0){
&&&&$chr&=&array();
&&&&foreach($needles&as&$needle){
&&&&&&&&$chr[]&=&strpos($haystack,$needle,$offset);
&&&&}
&&&&if(empty($chr))&return&false;
&&&&return&min($chr);
}
$string&=&"This&is&my&string,&very&simple.";
echo&strposa($string,array(".",",","&"));&//&2
echo&strposa($string,array("T"));&//&0
echo&strposa($string,array("Q","W"));&//&false
?&
Note&that&strpos()&will&return&false&if&you&supply&an&integer&(thus,&this&presumably&applies&to&float,&too)&as&needle.&For&example:&?php$id&=&2;&$text&=&'12345';if(strpos($text,&$id)&===&false){&&&echo&'Yes,&is&false';}?&Will&output&'Yes,&is&false',&a&behavior&which&may&not&be&very&intuitive&(you'd&think&it&would&be&covered&by&PHP's&type&juggling&feature).&This&can&be&easily&fixed&by&adding&$id&=&(string)$&above&the&strpos()&statement.
routine&to&return&-1&if&there&is&no&match&for&strpos
&?php
//instr&function&to&mimic&vb&instr&fucntion
function&InStr($haystack,&$needle)
{
&&&&$pos=strpos($haystack,&$needle);
&&&&if&($pos&!==&false)
&&&&{
&&&&&&&&return&$pos;
&&&&}
&&&&else
&&&&{
&&&&&&&&return&-1;
&&&&}
}
?&
A&function&that&return&the&first&occurance&of&a&number&in&a&string,&if&anyone&needs&it.Translation/prevod:Funkcija,&ki&vra?a&pozicijo&prve&?tevilke&v&besedi,&?e&jo&kdo&potrebuje.&?php&&&&function&firstNumPos($str)&{&&&&&&&&$poses&=&array();&//&will&be&storing&positions&of&the&numbers&&&&&&&&for($i&=&0;&$i&&&10;&++$i)&{&//&cycle&through&numbers&&&&&&&&&&&&if(($a&=&strpos($str,&(string)$i))&!==&false)&{&&&&&&&&&&&&&&&&$poses[]&=&$a;&&&&//&append&the&position&of&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//&the&first&occurance&of&the&number&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&if(isset($poses[0]))&{&//&if&array&not&empty&&&&&&&&&&&&sort($poses);&&&&&&&&//&sort&to&get&the&lowest&one&on&the&'bottom'&&&&&&&&&&&&return&$poses[0];&&&&//&and&return&it&&&&&&&&}&&&&&&&&return&false;&//&otherwise&return&false&&&&}&//&firstNumPos()?&
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
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;&
&&&&}
}
?&
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.
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
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
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&=&VERDADEROand&so&on...this&is&the&function:&?phpfunction&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!
I&wasn't&aware&of&the&!==&operator,&only&the&===&for&false.&I&was&using&this&code&on&strpos:
&?php
while(&!&($start=@strpos($source,$startTag,$end))&===&false)&{
&&//&...
}
?&
This&gave&a&false&if&the&string&was&found&at&position&0,&which&is&weird.&
However&using
&?php
while(($start=@strpos($source,$startTag,$end))&!==&false)&{
&&//&...
}
?&
Gives&no&such&error&and&seems&to&work&correctly
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.&?phpint&strnpos(string&$haystack,&mixed&$needle,&int&$occurence);?&Example:&?phpstrnpos("I&like&the&bananas.&You&like&coke.&We&like&chocolate.",&"like",&2);&//&24?&Here's&code&of&this&function:&?phpfunction&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;&&&&}?&
This&might&be&useful.
&?php
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
?&
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:
To know that a substring is present (in any position including 0), you can use either of:
(recommended)
(note: or greater than any negative number)
To know that a substring is at the start of the string, you must use:
To know that a substring is in any position other than the start, you can use any of:
(recommended)
(note: but not !== 0 which also equates to 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.
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:&?phpfunction&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);?&
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.
This&is&a&bit&more&useful&when&scanning&a&large&string&for&all&occurances&between&'tags'.&?phpfunction&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;}?&
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,&"&"));?&
If&you&want&to&check&for&either&IE6&or&7&individually.&?phpfunction&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;}?&
this&function&returns&the&text&between&2&strings:
&?php
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.
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&17strnpos($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;}?&
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...&?phpfunction&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];}&&&&&&&&?&
if&you&want&to&get&the&position&of&a&substring&relative&to&a&substring&of&your&string,&BUT&in&REVERSE&way:&?phpfunction&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;&&&&}&&&&//}?&
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)...
&?php
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.
If&you&want&to&find&positions&of&all&needle's&in&haystack,
you&can&use&this&one:
&?php
while&(($pos=strpos($haystack,$needle,$pos+1))!==false)&$pos_array[$i++]=$pos;
?&
But&mind,&that&it&will&find&from&second&char.&You&must&use&$pos=-1;&before&you&want&search&from&first&char.
&?php
$haystack="one&two&three&one&two&three&one&two&three&one&two&three&one";
$needle="one";
$pos=-1;
while&(($pos=strpos($haystack,$needle,$pos+1))!==false)&$pos_array[$i++]=$pos;
?&
$pos_array[0]&=&0
$pos_array[1]&=&14
$pos_array[2]&=&28
$pos_array[3]&=&42
$pos_array[4]&=&56
&?php
function&nthPos&($str,&$needles,&$n=1)&{
&&&&//&&&&finds&the&nth&occurrence&of&any&of&$needles'&characters&in&$str
&&&&//&&returns&-1&if&not&&$n&0&=&&count&backwards&from&end
&&&&//&&e.g.&$str&=&"c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg";
&&&&//&&&&&&&substr($str,&nthPos($str,&"/\\:",&-2))&=&&\Party\Phoebe.jpg
&&&&//&&&&&&&substr($str,&nthPos($str,&"/\\:",&4))&=&&\photos\Party\Phoebe.jpg
&&&&$pos&=&-1;
&&&&$size&=&strlen($str);
&&&&if&($reverse=($n&0))&{&$n=-$n;&$str&=&strrev($str);&}
&&&&while&($n--)&{
&&&&$bestNewPos&=&$size;
&&&&for&($i=strlen($needles)-1;$i&=0;$i--)&{
&&&&&&&&$newPos&=&strpos($str,&$needles[$i],&$pos+1);
&&&&&&&&if&($newPos===false)&$needles&=&substr($needles,0,$i)&.&substr($needles,$i+1);
&&&&&&&&else&$bestNewPos&=&min($bestNewPos,$newPos);&}
&&&&if&(($pos=$bestNewPos)==$size)&return&-1;&}
&&&&return&$reverse&?&$size-1-$pos&:&$pos;
}
?&
Csaba&Gabor&from&Vienna
if&you&want&need&a&fast&function&to&find&the&first&occurrence&of&any&ch&element&of&an&needle&array&this&function&might&be&of&use:&&?php$eurl&=&strpos_needle_array($text,&array('"'=&0,'\''=&0,'&'=&0,&'&'=&0,&"\n"=&0),&$surl);function&strpos_needle_array(&&$text,&$needle_ary,&$offset=0){&&&&&&&&for($ch_pos=$offset;$ch_pos&strlen($text);$ch_pos++){&&&&&&&&if(isset($needle_ary[$text[$ch_pos]])){&&&&&&&&&&&&return&$ch_pos;&&&&&&&&}&&&&}&&&&return&false;}?&
this&function&takes&a&space-deliminted&string&as&a&list&of&potential&needles&and&runs&it&against&another&string&as&a&haystack.
the&number&of&positive&matches&of&needles&within&the&haystack&is&returned&as&a&rounded&percentile.
&?php
function&keyMatch($needles,$haystack)&{
&&&&$nArray=split("&",$needles);
&&&&$found=0;
&&&&$best=count($nArray);
&&&&&&for($i=0;$i&count($nArray);$i++)&{
&&&&&&&&$pzn=strpos(strtoupper($haystack),strtoupper($nArray[$i]));
&&&&&&&&if&($pzn&-1)&{&$found++;&}
&&&&&&&}
&&&&$pct=($found*100)/$best;
&&&&return&round($pct);
}
$test&=&keyMatch("the&quick&wolf","the&quick&brown&fox&jumps&over&the&lazy&dog");
echo($test);
?&
(because&"the"&and&"quick"&were&found&but&"wolf"&was&not)
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.
&?php
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;
}
?&
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;}?&
here&a&little&function&for&tag&parsing
&?php
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;
}
?&
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;
&&&&}
}
?&
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
Code&like&this:&?phpif&(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:&?phpfunction&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&useif&(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);}?&
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;
&&&&&&&&&&&&
&&&&&&&&}
&&&&}
&&&&return&($found);
}
?&
counting&the&occurrences&of&a&substring,&recursive-style&instead&of&looping.
&?php
function&countSubstrs($haystack,&$needle)
{
&&&&return&(($p&=&strpos($haystack,&$needle))&===&false)&?&0&:&(1&+&countSubstrs(substr($haystack,&$p+1),&$needle));
}
?&
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);
}
?&
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&
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;
}
?&

我要回帖

更多关于 php 查找特定字符 的文章

 

随机推荐