Removing the filename extension from a string - php

I'm creating a breadcrumb script like this:
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
echo ' » '.$dirlist[$i].'';
?>
If form url is http:// domain /school/students.php,
the result is like this: ( home » school » students.php )
Question: How to eliminate the extension .php file students.php,
be like this ( home » school » students ) ??

No matter how long is the extension or its name, this will work :
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++) {
$result = $dirlist[$i];
if ($i == ($count-1)) { // if last element
$lastDot = strripos($result,'.') ;
$result = substr($result,0,$lastDot) ;
}
echo ' » '.$result.'';
}
?>

how about using string replacement?
Here's a bit of code that may point you in the right direction, replacing your for loop.
for ($i = 0; $i < $count; $i++) {
$label = str_replace('.php', '', $dirlist[$i]);
echo ' » '.$label.'';
}

Try deducting string
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
if(!isset($dirlist[$i+1]))
{
echo ' » '.substr($dirlist[$i],0,-4).'';
}
else
{
echo ' » '.$dirlist[$i].'';
}
?>
this will work.

Related

How to make the url display hostname without www?

How to make the url display hostname without www?
If the URL is
https://www.google.com/search/
How to make it like this?
google.com
My code
$rgx25 = '/\<a class\=\"live\" rel\=\"nofollow\" href\=\"(|https:\/\/|http:\/\/)(|www\.)(.*?)\" target\=\"\_blank\"\>(.*?)\<\/a\>/iu';
if (preg_match_all($rgx25, $story['text'], $matches))
{
foreach ($matches[0] as $k => $match)
{
$url = $matches[1][$k] . $matches[2][$k] . $matches[3][$k];
}
}
$url = 'http://sub.example.com/path?googleguy=googley';
$test = parse_url($url);
$string = explode('.',$test["host"]);
$top_lev_dom = array("com","net","us","gov","io","xyz","org","int","edu");
$output;
$end = false;
$pos = 0;
$pos2;
for($i = 0; $i < count($string); $i++){
for($x = 0; $x < count(top_lev_dom); $x++){
if($string[$i]==$top_lev_dom[$x]){
$pos = $i;
$pos2 = $i - 1;
$end = true;
break;
}
if($end == true){break;}
}
if($end == true){break;}
}
if($pos==0){
$output = "error";
}else{
$output.=$string[$pos2].".".$string[$pos];
}
echo $output;
example.com

getting directory of page using php

what i am trying to do is to get directory of my page like this
Home / Clothes / Something
i have tried this but i didn't understand a lot in this but it doesn't work as i want it
<?php
// current directory
echo getcwd() . "\n";
chdir('cvs');
// current directory
echo getcwd() . "\n";
?>
here's example what i need to do
my page is example.com/clothes/something.php
and on that page "something.php" i want to echo out something like this
Home / clothes / Something
i forget what this was called but hope you understand
<?php
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $parts[$i])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $parts[$i]);
};
};
};
?>
Try something like this:
$subPath = '';
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= $segment.'/';
echo "$segment / ";
}
You may need to tweak it a bit, but that's the basic idea.
[EDIT]
Or maybe something like this:
$Pages = [
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
];
$subPath = '';
$BreadCrumbs = [];
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= '/'.$segment;
$BreadCrumbs[] = "$Pages[$subPath]";
}
echo implode(' > ', $BreadCrumbs);
If your version of PHP is before 5.4.0, then you'll need a different syntax for the arrays:
$Pages = array(
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
);
$BreadCrumbs = array();
[EDIT]
OK, one last go:
<?php
$Pages = array(
'clothes' => 'Clothes',
'something' => 'Something'
);
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $Pages[$parts[$i]]);
};
};
};
?>

PHP Link Shortener

Zack here.. I've recently run into a spot of trouble with my URL Shortener.. Can you check the below code for errors? Thanks so much!
<?php
$db = new mysqli("localhost","pretzel_main","00WXE5fMWtaVd6Dd","pretzel");
function code($string_length = 3) {
$permissible_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_length = strlen($permissible_characters);
$random = '';
for ($i = 0; $i < $string_length; $i++) {
$random .= $permissible_characters[rand(0, $char_length - 1)];
}
return $random;
}
if (substr($_POST['long'], 0, 7) == http://) {
$url = $_POST['long'];
} elseif (substr($_POST['long'], 0, 8) == https://) {
$url = $_POST['long'];
} else {
$url = "http://".$_POST['long'];
}
$result = $db->prepare("INSERT INTO links VALUES('',?,?)");
$result->bind_param("ss",$url, $title);
$result->execute();
$title = $code();
?>
Good luck, and Thanks in advance!
- Zack
Try this :
<?php
$db = new mysqli("localhost","pretzel_main","00WXE5fMWtaVd6Dd","pretzel");
function code($string_length = 3) {
$permissible_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$char_length = strlen($permissible_characters);
$random = '';
for ($i = 0; $i < $string_length; $i++) {
$random .= $permissible_characters[rand(0, $char_length - 1)];
}
return $random;
}
if (substr($_POST['long'], 0, 7) == "http://") {
$url = $_POST['long'];
} elseif (substr($_POST['long'], 0, 8) == "https://") {
$url = $_POST['long'];
} else {
$url = "http://".$_POST['long'];
}
$result = $db->prepare("INSERT INTO links VALUES('ss','$url','$title')");
$result->execute();
$title = code(); // no need of $ sign here
?>

PHP strings concatenation

My code cycles through a CSV file, converting it to XML:
<?php
for ($i = 1; $i < $arraySize; $i++) {
$n = 0;
if (substr($csv[$i][0], 0, 1) == $let) {
$surName = $dom->createElement('name');
$name = $csv[$i][0];
$nameText = $dom->createTextNode($name);
$surName->appendChild($nameText);
$text = str_replace(chr(94), ",", $csv[$i][4]);
$n = $i + 1;
$next = $csv[$n][0];
while ($next == 'NULL') {
$repl = str_replace(chr(94), ",", $csv[$n][4]);
$text = $repl;
$n++;
$next = $csv[$n][0];
}
$bio = $dom->createElement('bio');
$bioText = $dom->createTextNode($text);
$bio->appendChild($bioText);
$person = $dom->createElement('person');
$person->appendChild($surName);
$person->appendChild($bio);
$people->appendChild($person);
}
}
$xmlString = $dom->saveXML();
echo $xmlString;
?>
The problem is the $text = $repl; Typing $text .= $repl; brings:
error on line 1 at column 1: Document is empty.
but omitting the . just gives the last line of text.
the backup code works:
public function test($let){
$csv = $this->readCSV("data\AlphaIndex1M.csv");
$arraySize=sizeof($csv);
$let = strtoupper($let);
//echo '';
for($i=1; $i
echo $csv[$i][0];// .'
echo ', -->'.$csv[$i][4];
$n = $i+1;
$next = $csv[$n][0];
//if($next == 'NULL'){ }
while($next == 'NULL'){
echo $csv[$n][4]. " ";
$n++;
$next=$csv[$n][0];
}
//echo ''
echo '';
}
}
//echo ''
}
You have to initialize your $text before you can append stuff!
So write this before you use it:
$test = "";
(before the while loop or even before the for loop if you want all to be appended)

Sort result alphabetically

function printAll($dirName)
{
if (empty($leid)) { $leid = "1"; }
$root = $_SERVER['DOCUMENT_ROOT'];
$site = $_GET['site'];
$user = $_GET['user'];
$tag = "";
$dirs=array($dirName);
$files=array();
while($dir=array_pop($dirs)){
$handle=opendir($dir);
while($file=readdir($handle)){
if($file!='.' && $file!='..'){
$dest=$dir.'/'.$file;
$userid = str_replace("$root/", "", $dir);
$userid = str_replace("dl/$site","",$userid);
$userid = str_replace("/","",$userid);
if(is_file($dest)){
$files[]=$file;
$titrepost = htmlspecialchars($file);
$downloadlink = "$dest";
$downloadlink = str_replace("$root/", "", $downloadlink);
$za = new ZipArchive();
$za->open($downloadlink);
$leid = $leid + 1;
echo "<br>
<b>File = $file</b><br>
Userid = $userid
<br>";
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune = basename( $stat['name'] );
echo "$toune <br>";
}
} else {
$dirs[]=$dest;
}
}
}
}
return $files;
}
$site = $_GET['site'];
$currentdir = getcwd();
$source = "$currentdir/dl/$site";
if (!empty($user)) {
$source = "$currentdir/dl/$site/$user";
}
printAll($source);
This script will list all files inside a ZIP archive then echo the name of each files.
Now i'm having some trouble figuring how to sort the files names ($toune) alphabetically
Here's what i tried:
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune_arr[] = basename( $stat['name'] );
}
asort($toune_arr);
print_r($toune_arr);
But it doesn't work for this code, $toune_arr won't empty after each zip file is listed so each time the script output the filelist it contains the files of the previous zip archives.
Just reset your array in the begining of your function:
function printAll($dirName)
{
$toune_arr = array();
...

Categories