Jump to content

Any ideas for function?


DarkWater

Recommended Posts

The topic HTTP ROOT prompted me to make a function to break up the document root and remove the final directory.  I decided to make a function that returns an array with the position of each occurrence of a character in a string, so you can use it in a substr() or whatever.

Here it is:

<?php
function array_charpos($haystack, $needle) {

if (strlen($needle) > 1 || strlen($needle) < 1) {
	return false;
}

$look_in = str_split($haystack);
        foreach ($look_in as $k=>$v) {

           	if ($v == $needle) {
            		$found_at[] = $k;

             	}
}
if (is_array($found_at)) {
          	return $found_at;
}
else {
	return false;
}
}

//Usage: array array_strpos (string $haystack, string $needle)
$oldenv = '/var/www/vhosts/mysite.com/httpdocs';
$slash_pos = array_charpos($oldenv, "/");
print_r ($slash_pos);
$newenv = substr($oldenv, 0, $slash_pos['2']);
echo $newenv; //outputs 'var/www';
?>

 

Can anyone think of something I should add?

Link to comment
https://forums.phpfreaks.com/topic/102262-any-ideas-for-function/
Share on other sites

try

<?php
function remove_final($url){
$u = explode('/', $url);
$c = count($u) - 1;
if ($u[$c] == ''){
	unset($u[$c]);
	$c--;
}
unset($u[$c]);
return implode('/', $u);
}
echo remove_final('c:/a/b/c/d/');
?>

Oh, I already did the document root function without a problem.  I just felt the need to make a function that returns the position that  the char is at, because there isn't really one that returns ALL of the positions.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.