Break Path into multiple Paths - php

I have the following path for example:
/Test1/Test2/Test3
Sometimes this path can be for example:
/Test1/Test2/Test3/Test4/Test5 and so on...
What I would like to do is take this unknown path and translate it into sections which will ultimately result in a navigation URL such as:
/Test1
/Test1/Test2
/Test1/Test2/Test3
and so on...
It's difficult to supply you with any code examples because many of the things I have attempted have resulted in no good results.
I assume I need to explode() the path using / as the delimiter and then splice it together somehow. I'm really at a loss here.
Does anyone have any suggestions I can try?

<?php
$path = '/Test1/Test2/Test3/Test4/Test5';
$explode = explode('/', $path);
$count = count($explode);
$res = '';
for($i = 1; $i < $count; $i++) {
echo $res .= '/' . $explode[$i];
echo '<br/>';
}
Returns:
/Test1
/Test1/Test2
/Test1/Test2/Test3
/Test1/Test2/Test3/Test4
/Test1/Test2/Test3/Test4/Test5

Here is how you get your array segments:
$path = '/Test1/Test2/Test3/Test4/Test5'; // or whatever your path is
$segments = explode('/', ltrim('/',$path));
If I understand you, then what you want to do is to build an array that is like
Array(
[0] => '/Test1'
[1] => '/Test1/Test2'
...
)
So you could just loop through your array and build up this new array
$paths_from_segments = array();
$segment_count = count($sgements);
$path_string = '';
foreach($sgement as $segment) {
$path_string .= '/' . $segment;
$paths_from_segments[] = $path_string;
}
var_dump($paths_from_segments);

Not exactly what you mean by "splice it together", but from the sounds of it you're looking for PHP's implode(), which is explode() in reverse.
explode("/", "test1/test2");
// result:
// Array
// (
// [0] => test1
// [1] => test2
// )
implode("/", Array("test1", "test2"));
// result:
// "test1/test2"

Related

seperate string and remove url parameters

I have this code, the part I am looking for is the number from the url 1538066650683084805
I use this example
$tweet_url = 'https://twitter.com/example/status/1538066650683084805'
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
Which works however sometimes on phones, When people copy and paste the url it has parameters on the end of it like this;
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
When a URL is exploded with the URL above the code doesn't work, how do I get the number 1538066650683084805 in both uses.
Thanks so much.
I would suggest using parse_url to get just the path, then separate that out:
$url = parse_url('https://twitter.com/example/status/1538066650683084805?q=2&t=1');
/*
[
"scheme" => "https",
"host" => "twitter.com",
"path" => "/example/status/1538066650683084805",
"query" => "q=2&t=1",
]
*/
$arr = explode("/", $url['path']);
$tweetID = end($arr);
I would explode first on the question mark and just look at the index 0 .. THEN explode the slash ...
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweet_url = explode('?', $tweet_url)[0];
$arr = explode("/", $tweet_url);
$tweetID = end($arr);
If the question mark does not exist -- It will still return the full URL in $tweet_url = explode('?', $tweet_url)[0]; so it's harmless to have it there.
And this is just me .. But I would write it this way:
$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweetID = end(
explode("/",
explode('?', $tweet_url)[0]
)
);
echo $tweetID . "\n\n";

find regex in glob() search filesin directory php

I'm serching files in a directory
PROBLEM
I need to retrieve files whose directory matches with the word entered
I need something like: glob (gifs/[like $varSearched]/*.gif)
Directory
gifs/hello/1.gif
gifs/hello/2.gif
gifs/hello/3.gif
gifs/claps/1.gif
gifs/claps/2.gif
gifs/wow/1.gif
gifs/wow/2.gif
PATH PHP (it works but its needed to type all the file directory "hello", "wow", "claps" to retrieve the results). What I need is to type one or two letter only to retrieve the results
$dir="o"; // "o" is the searched term
$mdir = "../gifs/".$dir."/";
$files = glob($mdir.'*.gif');
foreach ($files as $gif){
$title = basename(dirname($gif));
$arr[] = $title." - ".$gif;
}
$arr= implode("",$arr);
echo $arr;
EXPECTED RESULTS
gifs/hello/1.gif
gifs/hello/2.gif
gifs/hello/3.gif
gifs/wow/1.gif
gifs/wow/2.gif
As in case with file name, you can add * as a placeholder for any symbol in directory name:
$mdir = "../gifs/*".$dir."*/"; // see `*` here?
$files = glob($mdir.'*.gif');
// rest of the code here
You can also do this.
<?php
$search = "c";
$dir = "gifs/";
$folder = exec( "ls -d ".$dir.$search."*" );
$files = glob($folder.'/*.gif');
foreach ( $files as $gif ) {
$title = basename( dirname( $gif ) );
$arr[] = $title." - ".$gif;
}
print_r( $arr );
$arr = implode( "", $arr );
//echo $arr."\n";
Replacing the $search = "c"; with whatever directory letter you want and replacing $dir = "gifs/"; with whatever your filepath is.
Print_r with search letter "c"
Array
(
[0] => claps - gifs/claps/1.gif
[1] => claps - gifs/claps/2.gif
)
Print_r with search letter "h"
Array
(
[0] => hello - gifs/hello/1.gif
[1] => hello - gifs/hello/2.gif
[2] => hello - gifs/hello/3.gif
)
You could also wrap this in a function and pass it the two arguments $search and $dir and add a return $arr at the end.

parse string for subdomain in php

How can i find if a string has subdomain existing if there is no scheme / host present.
eg: $url="sub.main.com/images/sample.jpg";
I am trying to parse the url for images, and I am using parse_url for most cases.
But given the url strings can some in different flavors,
eg:
/images/sample.jpg
//main.com/images/sample.jpg
images/sample.jpg
etc, I am trying to address the different cases one by one. Right now, I am finding it hard to detect if a string has subdomain present or not.
so for a string such as $url="sub.main.com/images/sample.jpg";` i would like to extract the subdomain, and for a string such as images/sample.jpg, i would like to find out that there is no subdomain
Interesting problem. I've fiddled around with this for a while; this method inevitably isn't perfect, but it may start you down the right path.
My solution begins with the two source files in this repository: https://github.com/usrflo/registered-domain-libs/tree/master/PHP
First, you may need to modify regDomain.inc.php to change an instance of $signingDomainParts = split('\.', $signingDomain); to $signingDomainParts = preg_split('/\./', $signingDomain); if split is deprecated in your php version.
Once you've got those saved, try this testing code, I put all of the URLs mentioned in the thread here as test cases:
<?php
require_once("effectiveTLDs.inc.php");
require_once("regDomain.inc.php");
$tests = Array("/images/sample.jpg","//main.com/images/sample.jpg","images/sample.jpg", "sub.main.com/images/sample.jpg", "http://www.example.com/www.google.com/sample.jpg", "amazon.co.uk/images/sample.jpg", "amazon.com/images/sample.jpg", "http://sub2.sub.main.co.uk/images/sample.jpg", "sub2.sub.main.co.uk/images/sample.jpg");
foreach($tests as $test)
{
echo "Attempting $test.<BR/>";
$one = parse_url($test);
if(!array_key_exists("host", $one))
{
echo "Converting to: http://$test";
echo "<BR/>";
$one = parse_url("http://$test");
}
if(!$one){echo "<BR/>";continue;}
echo "parse_url parts: ";
print_r($one);
echo "<BR/>";
if($one && array_key_exists("host", $one))
{
$domain = getRegisteredDomain($one["host"], $tldTree);
if(sizeof($domain))
{
$two = explode(".", $domain);
echo "domain parts: ";
print_r($two);
echo "<BR/>";
if(sizeof($two))
{
$three = array_diff(explode(".", $one["host"]), $two);
if(sizeof($three))
{
echo "Hark! A subdomain!: ";
print_r($three);
echo "<BR/>";
}
}
}
}
echo "<BR/>";
}
?>
This code identifies the following of the test-cases as having subdomains:
Attempting sub.main.com/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub )
Attempting http://www.example.com/www.google.com/sample.jpg.
Hark! A subdomain!: Array ( [0] => www )
Attempting http://sub2.sub.main.co.uk/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub2 [1] => sub )
Attempting sub2.sub.main.co.uk/images/sample.jpg.
Hark! A subdomain!: Array ( [0] => sub2 [1] => sub )
Try this code
<?php
$url = 'sub.main.com/images/sample.jpg';
$arr = explode('/',$url);
$domain = $arr[0];
$string = $arr[1];
$arr2 = explode('.',$domain);
if(count($arr2)>2) {
$subdomain = $arr2[0];
echo $subdomain;
}
?>
<?php
$url = 'http://sub.main.com/images/sample.jpg';
$arr = explode('/',$url);
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
{
$main_domain=$regs['domain'];
}
$host=$pieces['host'];
$path=$pieces['path'];
if($host != $main_domain)
{
$arr2 = explode('.',$host);
$subdomain = $arr2[0];
echo $subdomain;
}
$string=substr($path,1,strlen($path));
?>
Try the following:
<?php
$url="sub.main.com/images/sample.jpg";
preg_match('#^(?:http://)?([^.]+).?([^/]+)#i',$url, $hits);
print_r($hits);
?>
This should output something like:
Array ( [0] => sub.main.com [1] => sub [2] => main.com )

How can I remove the file extension from each string in a PHP array?

I have an array of strings, each string containing the name of an image file:
$slike=(1.jpg,253455.jpg,32.jpg,477.jpg);
I want new array, to look like this:
$slike=(1,253455,32,477);
How can I remove the file extension from each string in this array?
If you're working with filenames, use PHP's built in pathinfo() function. there's no need to use regex for this.
<?php
# your array
$slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
# if you have PHP >= 5.3, I'd use this
$slike = array_map(function($e){
return pathinfo($e, PATHINFO_FILENAME);
}, $slike);
# if you have PHP <= 5.2, use this
$slike = array_map('pathinfo', $slike, array_fill(
0, count($slike), PATHINFO_FILENAME
));
# dump
print_r($slike);
Output
Array
(
[0] => 1
[1] => 253455
[2] => 32
[3] => 477
)
Using preg_split in foreach
foreach ($slike as &$value) {
$split = preg_split('/\./', $value);
$value = $split[0]
}
Change the regex to /[^.]+/ to include a.b.jpg as well.
Regular expressions are your friend on this one. I'm assuming that by brackers, you mean an array.
$k = count($slike);
for ($i = 0; $i < $k; $i++) {
$extpos = strrpos($slike[$i],".");
$slike[$i] = substr($slike[$i],0,$extpos);
}
This is no longer regex-dependent, and benchmarks faster than pathinfo().
Try this one:
$slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
$slike = array_map(function($e){
$e = explode('.', $e);
return $e[0];
}, $slike);
echo "<pre>";
print_r($slike);
echo "</pre>";

How to recursively create a multidimensional array?

I am trying to create a multi-dimensional array whose parts are determined by a string. I'm using . as the delimiter, and each part (except for the last) should be an array
ex:
config.debug.router.strictMode = true
I want the same results as if I were to type:
$arr = array('config' => array('debug' => array('router' => array('strictMode' => true))));
This problem's really got me going in circles, any help is appreciated. Thanks!
Let’s assume we already have the key and value in $key and $val, then you could do this:
$key = 'config.debug.router.strictMode';
$val = true;
$path = explode('.', $key);
Builing the array from left to right:
$arr = array();
$tmp = &$arr;
foreach ($path as $segment) {
$tmp[$segment] = array();
$tmp = &$tmp[$segment];
}
$tmp = $val;
And from right to left:
$arr = array();
$tmp = $val;
while ($segment = array_pop($path)) {
$tmp = array($segment => $tmp);
}
$arr = $tmp;
I say split everything up, start with the value, and work backwards from there, each time through, wrapping what you have inside another array. Like so:
$s = 'config.debug.router.strictMode = true';
list($parts, $value) = explode(' = ', $s);
$parts = explode('.', $parts);
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($parts);
Definitely rewrite it so it has error checking.
Gumbo's answer looks good.
However, it looks like you want to parse a typical .ini file.
Consider using library code instead of rolling your own.
For instance, Zend_Config handles this kind of thing nicely.
I really like JasonWolf answer to this.
As to the possible errors: yes, but he supplied a great idea, now it is up to the reader to make it bullet proof.
My need was a bit more basic: from a delimited list, create a MD array. I slightly modified his code to give me just that. This version will give you an array with or without a define string or even a string without the delimiter.
I hope someone can make this even better.
$parts = "config.debug.router.strictMode";
$parts = explode(".", $parts);
$value = null;
while($parts) {
$value = array(array_pop($parts) => $value);
}
print_r($value);
// The attribute to the right of the equals sign
$rightOfEquals = true;
$leftOfEquals = "config.debug.router.strictMode";
// Array of identifiers
$identifiers = explode(".", $leftOfEquals);
// How many 'identifiers' we have
$numIdentifiers = count($identifiers);
// Iterate through each identifier backwards
// We do this backwards because we want the "innermost" array element
// to be defined first.
for ($i = ($numIdentifiers - 1); $i >=0; $i--)
{
// If we are looking at the "last" identifier, then we know what its
// value is. It is the thing directly to the right of the equals sign.
if ($i == ($numIdentifiers - 1))
{
$a = array($identifiers[$i] => $rightOfEquals);
}
// Otherwise, we recursively append our new attribute to the beginning of the array.
else
{
$a = array($identifiers[$i] => $a);
}
}
print_r($a);

Categories