How to get directory name from file path using php - php

I am trying to get dir name from my file path: Currently below is my output:
Array
(
[path] => \documentLibrary\work\marketingProcess\BusinessMarketing\Design\Images\02_Product_Images\04_SHORT-RANGE\NINA\01_NINA-B1\source_WEB
)
and I want to get second last name which is (01_NINA-B1). What I am trying is:
echo "<pre>".print_r(dirname($results),true)."</pre>"; die;
when I add dirname above it displays nothing. What can I try next?
$query = db_select('network_drive','networkd');
$query
->fields('networkd', array('path'))
->condition('ndid',$networkdriveid,'=')
->orderBy('networkd.ndid');
$results = $query->execute();
echo "<pre>".print_r(dirname($results['path']),true)."</pre>"; die;

This looks like a plain string operation:
split the string
get the desired element
Maybe like this:
$s = '/documentLibrary/work/marketingProcess/BusinessMarketing/Design/Images/02_Product_Images/04_SHORT-RANGE/NINA/01_NINA-B1/source_WEB';
$a = explode(DIRECTORY_SEPARATOR, dirname($s)); //removes source_WEB and splits the string
echo array_pop($a); //gets the last element '01_NINA-B1'
Demo

Is this drupal? from my research I found out that db_select is a drupal function.
Can you try this one? it will attempt to explode the path string and find the second last element, if none is found it will return "N/A"
$query = db_select('network_drive','networkd');
$query
->fields('networkd', array('path'))
->condition('ndid',$networkdriveid,'=')
->orderBy('networkd.ndid');
$results = $query->execute();
foreach($results as $result){
$array = explode("\\", $result->path);
echo isset($array[count($array) - 2]) ? $array[count($array) - 2] : "N/A";
}

Related

Trim the content of system()?

I'm trying to print out all the users in active directory using system("dsquery user"); in php, my problem is getting it trimmed down so I have an array containing all the users and nothing else, atm this is my code:
<?php
$test = system("dsquery user");
$teste = explode('CN=', $test);
print_r($teste);
$user = trim($teste[1], ",");
echo "<br \>" . $user;
?>
I can only fetch one user atm because the explode deletes everything else..
Any help is appreciated, basically what I wan't to have in the end is something like this:
$user[0] = Administrator
$user[1] = kbgrt
$user[2] = asdasd
This is the output:
"CN=Administrator,CN=Users,DC=domain,DC=local" "CN=Guest,CN=Users,DC=domain,DC=local" "CN=krbtgt,CN=Users,DC=Domain,DC=local" "CN=doctor.scripto,CN=Users,DC=domain,DC=local" –
I hope you understand otherwise comment and I'll try to explain in another way.
Its not always easy to parse output from commands, if they are not designad for it. However a good start is to try to simplify it as much as possible and see patterns. However hope the code bellow will work for you I try to commented it as much as possible.
I have started with your output from system("dsquery user");
$test = '"CN=Administrator,CN=Users,DC=domain,DC=local" "CN=Guest,CN=Users,DC=domain,DC=local" "CN=krbtgt,CN=Users,DC=Domain,DC=local" "CN=doctor.scripto,CN=Users,DC=domain,DC=local"';
To make it easier I remove spaces and " from the string
$test = str_replace(' ', ',', $test);
$test = str_replace('"', '', $test);
Now we are ready to split the string on , so we get an array $teste that has elements that starts with LDIF values("DC=" or "CN=" in our case)
$teste = explode(',', $test);
Since some users are unwanted I add an array to exclude them. Also create an array $users to keep the result.
$users = array();
$exclude_users = array("Users", "doctor.scripto");
Then its just to iterate over array and split each element, so we get the LDIF part in position 0 and name in position 1. Add the name, if position 0 is equal to CN and name in position 1 is not in the list of excluded users.
foreach ($teste as $value) {
$data = explode('=', $value);
if($data[0] == 'CN' && !in_array($data[1], $exclude_users)) {
$users[] = $data[1];
}
}
print_r($users);
Here is the result:
Array
(
[0] => Administrator
[1] => Guest
[2] => krbtgt
)

Isolate substring at end of string after a specific substring

My query generates a result set of UID values which looks like:
855FM21
855FM22
etc
I want to isolate the last number from the UID which it can be done by splitting the string.
How to split this string after the substring "FM"?
To split this string after the sub string "FM", use explode with delimiter as FM. Do like
$uid = "855FM22";
$split = explode("FM",$uid);
var_dump($split[1]);
You can use the explode() method.
<?php
$UID = "855FM21";
$stringParts = explode("FM", $UID);
$firstPart = $stringParts[0]; // 855
$secondPart = $stringParts[1]; // 21
?>
use explode function it returns array. to get the last index use echo $array[count($array) - 1];
<?php
$str = "123FM23";
$array = explode("FM",$str);
echo $array[count($array) - 1];
?>
For it,please use the explode function of php.
$UID = "855FM21";
$splitToArray = explode("FM",$UID);
print_r($splitToArray[1]);
Have you tried the explode function of php?
http://php.net/manual/en/function.explode.php
As a matter of best practice, never ask for more from your mysql query than you actually intend to use. The act of splitting the uid can be done in the query itself -- and that's where I'd probably do it.
SELECT SUBSTRING_INDEX(uid, 'FM', -1) AS last_number FROM `your_tablename`
If you need to explode, then be practice would indicate that the third parameter of explode() should set to 2. This way, the function doesn't waste any extra effort looking for more occurrences of FM.
echo explode('FM', $uid, 2)[1]; // 21
If you want to use php to isolate the trailing number in the uid, but don't want explode() for some reason, here are some wackier / less efficient techniques:
$uid = '855FM21';
echo strtok($uid, 'FM') ? strtok('FM') : ''; // 21
echo preg_replace('~.*FM~', '', $uid); // 21
echo ltrim(ltrim($uid, '0..9'), 'MF'); // 21
$uid = '123FM456';
$ArrUid = split( $uid, 'FM' );
if( count( $ArrUid ) > 1 ){
//is_numeric check ?!
$lastNumbers = $ArrUid[1];
}
else{
//no more numbers after FM
}
You can also use regular expressions to extract the last numbers!
a simple example
$uid = '1234FM56';
preg_match( '/[0-9]+fm([0-9]+)/i', $uid, $arr );
print_r($arr); //the number is on index 1 in $arr -> $arr[1]

Remove parameter from link

I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number

Join array elements with a string

I want join array elements with a string (ex:-), i tried it with implode, but it don't work in my code.
How can fix it?
PHP:
<?php
$count = 1;
$ttttt = json_decode('["110,2"]');
$nnnnn = array("110","1","2");
$fffff = array('name','day','last');
$Rtp = str_replace($nnnnn, $fffff, $ttttt, $count);
echo implode(" - ", $Rtp); // This output is as: name,last
?>
DEMO: http://codepad.viper-7.com/ZNiBWy
You JSON is not valid the way you are expecting it, it generates only one value 110,2.
Change it to ["110","2"] and your implode should be ok.
You have an array $ttttt = array(110, 2) .
You then replace all values in this array as follows 110 -> name, 2 -> last and 1 -> day, using str_replace.
So (110, 2) becomes ("name", "last")

Array values into string

I've been searching and searching and can't find anything that works, but this is what I want to do.
This code:
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80',array('0D7EA7F06E07F56780D733F18F46DDBB826DCB65'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
Outputs this:
Array ( [0D7EA7F06E07F56780D733F18F46DDBB826DCB65] => Array ( [seeders] => 148 [completed] => 10 [leechers] => 20 [infohash] => 0D7EA7F06E07F56780D733F18F46DDBB826DCB65 ) )
And I want that seeder count into a string such as $seeds. How would I go about doing this?
Something like this?
$seeds = $ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders'];
you can user strval() to convert a number to a string.
$string = strval($number);
or you can cast it into a string:
$string = (string)$number;
in your context that would be:
$string = strval($ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders']);
However that odd string is also the first index of the array so you could also do it like this:
$string = strval($ret[0]['seeders']);
or if you want ot use only indexes ('seeders' is also the first index of the second array):
$string = strval($ret[0][0]);
if you just want the number then it's easy too:
$num = $ret[0][0];
It's not clear if you're looking to assign the array value(s?) as a separate variable(s?) or just to cast it into a string. Here's a nice way to accomplish all the above options, by assigning each array key as a separate variable with the matching array value:
$ret_vars = array_pop($ret);
foreach ($ret_vars as $variable_name=>$variable_value) :
${$variable_name} = (string)$variable_value;
endforeach;
In your original example, this would end up populating $seeders, $completed, $leechers and $infohash with their matching string values. Of course, make sure these variable names are not used/needed elsewhere in the code. If that's the case, simply add some sort of unique prefix to the ${} construct, like ${'ret_'.$variable_name}

Categories