note 68520 deleted from function.strstr by bjori

From: Date: Tue, 01 Aug 2006 08:56:38 +0000
Subject: note 68520 deleted from function.strstr by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-115390@lists.php.net to get a copy of this message
Note Submitter: repley at freemail dot it Reason: in docs ---- Bugfix of my previous post: now work if the position of $needle in $haystack was the 0th (first) character. Regards from Italy. <? //strxstr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]]) function strxstr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){ // Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character. if(strrpos($haystack, $needle) !== false){ //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_array = array("....unknown.txt.log.......gif.....jpeg", "/index.html", "index.html", "http://www.example.com/", "/folder_one/", "/folder_one/folder_two/", "folder_two/"); $needle_array = array(".", "/", ".", "/", "/", "/", "/"); $count_haystack = count($haystack_array); $count_needle = count($needle_array); if($count_haystack == $count_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 for($pointer = 0; $pointer < $count_haystack; $pointer++) { $haystack = $haystack_array[$pointer]; $needle = $needle_array[$pointer]; $a = strxstr($haystack, $needle, $l_inclusive, $r_inclusive); if($a){echo "Left: <strong>" . $a[0] . "</strong><br /> Right: <strong>" . $a[1] . "</strong><br /><br />";}else{echo "Failed!<br />";} } }else{ echo 'Count of "$haystack_array" and count of "$needle_array" are not equal!'; } //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 Thanks to all. Repley

« previous php.notes (#115390) next »