How to Grab the Name of the 2nd Folder Without the Path - php

The last question was marked as a duplicate so I'm reopening since $_SERVER['REQUEST_URI']: isnt what I'm looking for because it displays the entire path.
I need to just display the name of the 2nd folder alone without the path, without forward slashes and without the pagename
Here is the structure of the URL:
http://example.com/sub/THISFOLDER/page.php
the domain will change, so I'm looking for a solution that will work for any domain as long as it targets the 2nd folder.
What I want to do is something like this:
if THISFOLDER is named folder1 then { include("header2.php"); }

To fetch the current folder name use this method:
$arr = explode('/', dirname(__FILE__));
$whatyouneed = $arr[count($arr)-1];

<?php
$str = 'http://example.com/sub/THISFOLDER/page.php';
$parts = parse_url($str);
$folders = explode('/', $parts['path']);
var_dump($folders[2]);
Output:
string(10) "THISFOLDER"
I used parse_url so it will work easily regardless of the exact url structure.

If you always want to get the last folder before the php page. (Even if it is not the second you can use this code).
<?php
$thisPath = $_SERVER['PHP_SELF'];;
$pattern = '/(\W+)\/(\w+)\/(\w+)/';
$replacement = '$2';
echo preg_replace($pattern, $replacement, $string);
?>
Sorry, I don't have a php instance spun up to actually test this, but the way it should work is this:
Looking at it from back to front:
It will find normal word characters and hit the slash, that is accounted for by "/". Then it will look for more normal characters. The '/' is covered, then it will look for any possible non-white space character to cover the rest. You want the middle portion.

Related

Create link from Plaintext [duplicate]

Lets say that $content is the content of a textarea
/*Convert the http/https to link */
$content = preg_replace('!((https://|http://)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="$1">$1</a> ', nl2br($_POST['helpcontent'])." ");
/*Convert the www. to link prepending http://*/
$content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");
This was working ok for links, but realised that it was breaking the markup when an image is within the text...
I am trying like this now:
$content = preg_replace('!\s((https?://|http://)+[a-z0-9_./?=&-]+)!i', ' $1 ', nl2br($_POST['content'])." ");
$content = preg_replace('!((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$1">$1</a> ', $content." ");
As is the images are respected, but the problem is that url's with http:// or https:// format won't be converted now..:
google.com -> Not converted (as expected)
www.google.com -> Well Converted
http://google.com -> Not converted (unexpected)
https://google.com -> Not converted (unexpected)
What am I missing?
-EDIT-
Current almost working solution:
$content = preg_replace('!(\s|^)((https?://)+[a-z0-9_./?=&-]+)!i', ' $2 ', nl2br($_POST['content'])." ");
$content = preg_replace('!(\s|^)((www\.)+[a-z0-9_./?=&-]+)!i', '<a target="_blank" href="http://$2" target="_blank">$2</a> ', $content." ");
The thing here is that if this is the input:
www.funcook.com http://www.funcook.com https://www.funcook.com
funcook.com http://funcook.com https://funcook.com
All the urls I want (all, except name.domain) are converted as expected, but this is the output
www.funcook.com http://www.funcook.com https://www.funcook.com ;
funcook.com http://funcook.com https://funcook.com
Note an ; is inserted, any idea why?
try this:
preg_replace('!(\s|^)((https?://|www\.)+[a-z0-9_./?=&-]+)!i', ' $2 ',$text);
It will pick up links beginning with http:// or with www.
Example
You can't at 100%. Becuase there may be links such as stackoverflow.com which do not have www..
If you're only targeting those links:
!(www\.\S+)!i
Should work well enough for you.
EDIT: As for your newest question, as to why http links don't get converted but https do, Your first pattern only searches for https://, or http://. which isn't the case. Simplify it by replacing:
(https://|http://\.)
With
(https?://)
Which will make the s optional.
Another method to go about adding hyperlinks is that you could take the text that you want to parse for links, and explode it into an array. Then loop through it using foreach (very fast function - http://www.phpbench.com/) and change anything that starts with http://, or https://, or www., or ends with .com/.org/etc into a link.
I'm thinking maybe something like this:
$userTextArray = explode(" ",$userText);
foreach( $userTextArray as &$word){
//if statements to test if if it starts with www. or ends with .com or whatever else
//change $word so that it is a link
}
Your changes will be reflected in the array since you had the "&" before $userText in your foreach statement.
Now just implode the array back into a string and you're good to go.
This made sense in my head... But I'm not 100% sure that this is what you're looking for
I had similar problem. Here is function which helped me. Maybe it will fit your needs to:
function clHost($Address) {
$parseUrl = parse_url(trim($Address));
return str_replace ("www.","",trim(trim($parseUrl[host] ? $parseUrl[host].$parseUrl[path] : $parseUrl[path]),'/'));
}
This function will return domain without protocol and "www", so you can add them yourself later.
For example:
$url = "http://www.". clHost($link);
I did it like that, because I couldn't find good regexp.
\s((https?://|www.)+[a-z0-9_./?=&-]+)
The problem is that your starting \s is forcing the match to start with a space, so, if you don't have that starting space your match fails. The reg exp is fine (without the \s), but to avoid replacing the images you need to add something to avoid matching them.
If the images are pure html use this:
(?<!src=")((https?://|www.)+[a-z0-9_./?=&-]+)
That will look for src=" before the url, to ignore it.
If you use another mark up, tell me and I'll try to find another way to avoid the images.

PHP: replace relative top URL "../" with absolute domain URL

I want to convert relative URLs that starts with ../stuff/more.php to http://www.example.com/stuff/more.php in my RSS feed.
I used this PHP code to do so is the following:
$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$2$3', $content);
The result is wrong thought, it returns the URL like this
http://www.example.com/../stuff/more.php
Notice the ../ part hasn't been removed, please help!
So Basically..
This what I have: ../stuff/more.php
This is what I get (after running the code above): http://www.example.com/../stuff/more.php
This what I WANT: http://www.example.com/stuff/more.php
Adding (\.|\.\.|\/)* should work.
$content = preg_replace("#(<\s*a\s+[^>]href\s=\s*[\"'])(?!http)(../|../|/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);
Also, note $2$3 has been changed to $3$4
Edit:
Reduced to one alternative:
$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)(\.\.\/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);
Why don't you just replace the first 2 dots with the domain?
$result = str_replace('..', 'http://www.example.com', $contet, 1);
Use $_SERVER[HTTP_HOST] $_SERVER[REQUEST_URI] is the global variable in PHP to get the absolute url.
Well, I'll start looking at the regex. Most of it looks good (in fact, you've got a good enough regex here I'm a little surprised you're having trouble otherwise!) but the end is a bit weird -- better like this:
#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#
(Technically it would be better to capture the starting quote and make sure it's a matching ending quote, but chances are you won't have any problems there.
To remove the ../ I would do it apart from regex entirely:
foreach (array("<a href=\"http://../foo/bar\">",
"<a href=\"../foo/bar\">") as $content) {
echo "A content=$content<br />\n";
########## copy from here down to...
if (preg_match("#(<\s*a\s+[^>]*?href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#", $content, $m)) {
echo "m=<pre>".print_r($m,true)."</pre><br />\n";
if (substr($m[2], 0, 3) == '../')
$m[2] = substr($m[2], 3);
$content = $m[1].'http://www.example.com/'.$m[2].$m[3];
}
######### copy from above down to HERE
echo "B content=$content<br />\n";
}
(I included a mini-test suite around what you're looking for - you will need to take just the marked lines inside for your code.)
I found the solution thanks to everyone who helped me on this.
Here's the code I used:
$content = preg_replace("#(<a href=\"\.\.\/)#", '<a href="http://www.example.com/', $content);
it searches for <a href="../ and replace it with http://www.example.com/ it's not general but this works for me.

get a specific part of a string

I have the following url. http://domain.com/userfiles/dynamic/images/whatever_dollar_1318105152.png
Everything in the url can change except the userfiles part and the last underscore. Basically I want to get the part of the url which is userfiles/dynamic/images/whatever_dollar_ What is a good way to do this. I'm open or both JavaScript or php.
Use parse_url in PHP to split an url in its various parts. Get the path part that is returned. It contains the path without the domain and the query string.
After that use strrpos to find the last occurrance of the _ within the path.
With substr you can copy the first part of the path (up until the found _) and you're done.
You could, with JavaScript, try:
var string = "http://domain.com/userfiles/dynamic/images/whatever_dollar_1318105152.png";
var newString = string.substring(string.indexOf('userfiles'),string.lastIndexOf('_'));
alert(newString); // returns: "userfiles/dynamic/images/whatever_dollar" (Without quotes).
JS Fiddle demo.
References:
substring().
indexOf().
lastIndexOf().
Assuming your string is stored in $s, simply:
echo preg_replace('/.*(userfiles.*_).*/', '$1', $s);

Using PHP to split a URL

I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.
When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"
i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?
please le me know how this is accomplished or if you have more questions.
As ircmaxell has already stated in the comments, PHP does already have a function to parse a URL: parse_url.
And when you have the URL path (I assume your export? the path suffix plus the query indicator), you can use explode to split the path into its path segments:
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', $path);
You can then get the last path segment with one of the following:
end($segments)
$segments[count($segments)-1]
And to cope with trailing slashes, you can use rtrim($path, '/') to remove them.
All together:
$url = 'http://www.example.com/subfolders/export?';
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
echo end($segments);
A regular expression should do the trick, something like the below would work. This is what Django uses in their URL dispatcher
r'^export/$'
Regular expressions are strings matches that may also include variable matches. Because ? is included within ?, you have to do your split twice. Once on export? first, and a second pass on each of those with ? as your delimiter. As written below, you're just splitting on either of two different strings.
$first = preg_split('export\?', ...);
for ($first) {
array_push ($second,preg_split('\?', ...)');
}
That isn't perfectly valid PHP, but I hope it is close enough pseudocode.
Hey guys i ended up using an explode which looked for the string (export?) and then i used the preg split command to search for the \?. this provided me with the protion i was looking for. thanks guys.

regex to get current page or directory name?

I am trying to get the page or last directory name from a url
for example if the url is: http://www.example.com/dir/ i want it to return dir or if the passed url is http://www.example.com/page.php I want it to return page Notice I do not want the trailing slash or file extension.
I tried this:
$regex = "/.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*/i";
$name = strtolower(preg_replace($regex,"$2",$url));
I ran this regex in PHP and it returned nothing. (however I tested the same regex in ActionScript and it worked!)
So what am I doing wrong here, how do I get what I want?
Thanks!!!
Don't use / as the regex delimiter if it also contains slashes. Try this:
$regex = "#^.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*$#i";
You may try tho escape the "/" in the middle. That simply closes your regex. So this may work:
$regex = "/.*\.(com|gov|org|net|mil|edu)\/([a-z_\-]+).*/i";
You may also make the regex somewhat more general, but that's another problem.
You can use this
array_pop(explode('/', $url));
Then apply a simple regex to remove any file extension
Assuming you want to match the entire address after the domain portion:
$regex = "%://[^/]+/([^?#]+)%i";
The above assumes a URL of the format extension://domainpart/everythingelse.
Then again, it seems that the problem here isn't that your RegEx isn't powerful enough, just mistyped (closing delimiter in the middle of the string). I'll leave this up for posterity, but I strongly recommend you check out PHP's parse_url() method.
This should adequately deliver:
substr($s = basename($_SERVER['REQUEST_URI']), 0, strrpos($s,'.') ?: strlen($s))
But this is better:
preg_replace('/[#\.\?].*/','',basename($path));
Although, your example is short, so I cannot tell if you want to preserve the entire path or just the last element of it. The preceding example will only preserve the last piece, but this should save the whole path while being generic enough to work with just about anything that can be thrown at you:
preg_replace('~(?:/$|[#\.\?].*)~','',substr(parse_url($path, PHP_URL_PATH),1));
As much as I personally love using regular expressions, more 'crude' (for want of a better word) string functions might be a good alternative for you. The snippet below uses sscanf to parse the path part of the URL for the first bunch of letters.
$url = "http://www.example.com/page.php";
$path = parse_url($url, PHP_URL_PATH);
sscanf($path, '/%[a-z]', $part);
// $part = "page";
This expression:
(?<=^[^:]+://[^.]+(?:\.[^.]+)*/)[^/]*(?=\.[^.]+$|/$)
Gives the following results:
http://www.example.com/dir/ dir
http://www.example.com/foo/dir/ dir
http://www.example.com/page.php page
http://www.example.com/foo/page.php page
Apologies in advance if this is not valid PHP regex - I tested it using RegexBuddy.
Save yourself the regular expression and make PHP's other functions feel more loved.
$url = "http://www.example.com/page.php";
$filename = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
Warning: for PHP 5.2 and up.

Categories