note 48626 added to ref.strings

From: Date: Sun, 02 Jan 2005 16:32:44 +0000
Subject: note 48626 added to ref.strings
Groups: php.notes 
Request: Send a blank email to php-notes+get-82603@lists.php.net to get a copy of this message
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point. strnpos() - Find the nth position of needle in haystack. <?php function strnpos($haystack, $needle, $occurance, $pos = 0) { for ($i = 1; $i <= $occurance; $i++) { $pos = strpos($haystack, $needle, $pos) + 1; } return $pos - 1; } ?> Example: Give me everything up to the fourth occurance of '/'. <?php $haystack = "/home/username/www/index.php"; $needle = "/"; $root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4)); echo $root_dir; ?> Returns: /home/username/www Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically! ---- Manual Page -- http://www.php.net/manual/en/ref.strings.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48626 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48626&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48626&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#82603) next »