note 66409 added to function.strstr

From: Date: Sun, 21 May 2006 16:55:22 +0000
Subject: note 66409 added to function.strstr
Groups: php.notes 
Request: Send a blank email to php-notes+get-111786@lists.php.net to get a copy of this message
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(): http://www.php.net/manual/en/function.strrchr.php ---- Server IP: 213.92.11.19 Probable Submitter: 84.222.147.29 ---- X-Spam-Status: No, hits=3.3 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER, HTML_MESSAGE autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.strstr.php Edit -- http://master.php.net/note/edit/66409 Del: integrated -- http://master.php.net/note/delete/66409/integrated Del: useless -- http://master.php.net/note/delete/66409/useless Del: bad code -- http://master.php.net/note/delete/66409/bad+code Del: spam -- http://master.php.net/note/delete/66409/spam Del: non-english -- http://master.php.net/note/delete/66409/non-english Del: in docs -- http://master.php.net/note/delete/66409/in+docs Del: other reasons-- http://master.php.net/note/delete/66409 Reject -- http://master.php.net/note/reject/66409 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#111786) next »