Remove all before certain delimiter starting at end of string PHP - php

Hey, I need help isolating part of a url in PHP.
say I have
http://www.test.com/something/something/important/
How could I isolate the "important"
Thanks!

Use the basename() function for that.
echo basename('http://www.test.com/something/something/important/');
Result:
important

<?php
$url ='http://www.test.com/something/something/important/';
echo basename($url);
?>

Related

What is the PHP regex to get the parent directory of a page?

I have a page at:
http://somewebsite.com/1234/test/
How do I get the 1234 extracted from it with a PHP regex?
Don't use RegEx use parse_url() and explode().
For one level up, use dirname()
I like to avoid regex if I don't need it, so I would recommend you do it this way:
$url = explode("/", $_SERVER['PHP_SELF']);
Then you can reference the part of the url that you want using this:
$url[1]
If you need/want to use regex, I'll think about it for a second and try to post a solution later.
To just get the one above you can use
echo dirname("http://www.google.com/cake/lol");
Outputs
http://www.google.com/cake
Or for just the bit between the / and / you could do
var_dump(explode("/", "http://www.google.com/cake/lol"));
Or in regex
preg_match_all('#/([^/]*)/#',$sourcestring,$matches);
Perform regex on $_SCRIPT['REQUEST_URL'] or split it by '/' and get the first element => 1234
If the PHP was triggered by launching that URL, then these will probably be true:
$_SERVER['REQUEST_URI'] == "/1234/test/"
dirname($_SERVER['REQUEST_URI']) == "/1234"
basename(dirname($_SERVER['REQUEST_URI'])) == "1234"
preg_match(".*\/(\w+)\/(\w+)\/", "$url", $matches);
The parent directory is $matches[1].

PHP remove page name Regex - preg_replace

I have this url (several similar ones)..
images/image1/image1.jpg
images/images1/images2/image2.jpg
images/images2/images3/images4/image4.jpg
I have this regex: but I want it to strip away the image name from the string:
<?php $imageurlfolder = $pagename1;
$imageurlfolder = preg_replace('/[A-Za-z0-9]+.asp/', '', $pagename1);?>
the string would look like the url's above images/images2/images3/images4/ but without the image4.jpg
hope you can help
Thanks
For this particular purpose function dirname() would be sufficient:
<?php echo dirname('images/images2/images3/images4/image4.jpg'); ?>
Would return:
images/images2/images3/images4
I think you can use the dirname function
for instance (from that page)
dirname("/etc/passwd")
would print
/etc
A quite straightforward way to do it:
preg_replace("#(?<=/)[^/]+$#","",$your_string);
It will remove everything between the last / and the end of the string.
Edit: as many peopole pointed out, you can also use dirname which might proof faster…

html pattern to parse in php

i have a following pattern, inside the html file, that i would like to parse in php to get a link but for now i dont see a solution as i am trying to use QueryPath and my case is simply not a common dom element:
<script>
to.addVariable("site_name","http://www.sitename.com");
</script>
I just would like to return a link part of that pattern in order to print it.
Hope someone could recommend how to.
Thank you.
UPDATE: I would like to get http://www.sitename.com as a value from the code above using php, maybe with phpQuery or QueryPath.
Something like this I guess will work
<?PHP
$text = '
<script>
to.addVariable("site_name","http://www.sitename.com");
</script>
';
preg_match('#to\.addVariable\("site_name","([^"]+)"\);#', $text, $matches);
echo $matches[1];
?>
You can also use preg_match_all if you have more than one to.addVariable(... strings in your <script> section.
Try this regular exp:
$regex = '#to\.addVariable\("(.+?)", "(.+?)"\)#';
Then, use preg_match_all to get the matches. If you want to check that the URL is an actual URL, the get any regular expression to match URLs and place it in the second .+?, these patterns will match anything between "", so you should check that you have what you need unless you trust the source.
NOTE: I'm not so sure that " doesn't needs to be escaped in regex, so check it out
Hope I can help!
If you don't understand something drop a comment!

PHP Regex help, getting part of a link

I'm trying to write a regex in php that in a line like
<a href="mypage.php?(some junk)&p=12345&(other junk)" other link stuff>Text</a>
and it will only return me "p=12345", or even "12345". Note that the (some junk)& and the &(otherjunk) may or may not be present.
Can I do this with one expression, or will I need more than one? I can't seem to work out how to do it in one, which is what I would like if at all possible. I'm also open to other methods of doing this, if you have a suggestion.
Thanks
Perhaps a better tactic over using a regular expressoin in this case is to use parse_url.
You can use that to get the query (what comes after the ? in your URL) and split on the '&' character and then the '=' to put things into a nice dictionary.
Use parse_url and parse_str:
$url = 'mypage.php?(some junk)&p=12345&(other junk)';
$parsed_url = parse_url($url);
parse_str($parsed_url['query'], $parsed_str);
echo $parsed_str['p'];

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