Get values from url with PHP - php

I'm trying to get values from a url using php. With basename I only get the last part but i need the part before that as well.
This is the domain: http://mydomain.nl/first/second/third/
$url = parse_url($entry['source_url']);
$urlFragments = explode('/', $url);
$second = $urlFragments[0];
$third = $urlFragments[1];
I need to use part second and part third.

#idka-80 try this,
$url_components = parse_url($url);
echo "<pre>";
print_r(array_filter(explode("/",$url_components['path'])));

This script can help you
First of all, to make it simple I remove http:// part and then explode it with / and get a different part of the data which is separated by /
<?php
$url = "http://mydomain.nl/first/second/third/";
$url = str_replace("http://", "", $url);
$urlFragments = explode('/', $url);
$yourDomain = $urlFragments[0];
$first = $urlFragments[1];
$second = $urlFragments[2];
$third = $urlFragments[3];
echo $first . ", " . $second . ", " . $third;

As you can tell from the fatal error, you're making a wrong assumption about how parse_url() works:
Fatal error: Uncaught TypeError: explode(): Argument #2 ($string) must be of type string, array given
If you only want a specific fragment, you need to tell which one:
$url = parse_url($entry['source_url'], PHP_URL_PATH);
// ^ Also give it a better name, such as `$path`
You also possibly want to discard leading and trailing slashes:
$urlFragments = explode('/', trim($url, '/'));

Hopefully this will help
$url = 'http://mydomain.nl/first/second/third/';
$urlFragments = explode('/', $url);
echo $second = $urlFragments[4];
echo $third = $urlFragments[5];

Related

Extract particular point of URL in PHP

I'm trying to get a very specific part of a URL using PHP so that I can use it as a variable later on.
The URL I have is:
https://forums.mydomain.com/index.php?/clubs/11-Default-Club
The particular part I am trying to extract is the 11 part between the /clubs/ and -Default-Club bits.
I was wondering what the best way to do this was. I've seen examples on here that use a regex-esque parser but I can't wrap my head around it for this particular instance.
Thanks
Edit; this is what I've tried so far using an explode query, but it seems to give me all sorts of elements which are not present in the URL above:
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$url = array_filter($url);
$url = array_merge($url, array());
Which returns:
Array ( [0] => index.php?app=core&module=system&controller=widgets&do=getBlock&blockID=plugin_9_bimBlankWidget_dqtr03ssz&pageApp=core&pageModule=clubs&pageController=view&pageArea=header&orientation=horizontal&csrfKey=8e19769b95c733b05439755827a98ac8 )
If you expect that the string with dashes (11-Default-Club) will be always at the end you can try this:
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $url);
$string = end($urlParts);
$stringParts = explode('-', $string);
$theNumber = $stringParts[0]; // this will be 11
I'd rather be explicit:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$query = parse_url($url, PHP_URL_QUERY);
$pattern = '#^/clubs/(\d+)[a-zA-Z-]+$#';
$digits = preg_match($pattern, $query, $matches)
? $matches[1]
: null;
var_dump($digits);
Output:
string(2) "11"
If this URL structure is fix for all URLs in your site and you only want to get the integer/number/digit part of the URL:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$int = (int) filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $int;
If this url structure is fix for all URLs in your site then below is best way to get your value.
<?php
$url = "https://forums.mydomain.com/index.php?/clubs/11-Default-Club";
$url = explode('/', $url);
$url = array_filter($url);
$end = end($url);
$end_parts = explode('-',$end);
echo $end_parts[0];
Output:
11

finding the last occurrence of a string and replacing it

I have the following link as a string in php:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
I am trying to add the word BIG before the number so at the end I will have:
$url = 'http://www.example.com/assets/images/temp/big10.jpg';
I am currently accomplishing that by using explode on / then adding big to the last array. My only issue is that in the future, this link might have less / i.e.: http://www.example.com/assets/10.jpg. In this case, my explode statement will not work. Is there a better way to add the word big after the last occurance of /?
I also came up with this method:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$filename = substr(strrchr($url, "/"), 1); // returns 10.jpg
$newfilename = 'big'.substr(strrchr($url, "/"), 1); // returns big10.jpg
$newurl = str_replace($filename,$newfilename,$url); // replaces 10.jpg with big.jpg
According to description as mentioned into above question as a solution to it please try executing following code snippet .
<?php
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileName = basename($url);
$newFileName = 'big' . $fileName;
$url = str_ireplace($fileName, $newFileName, $url);
echo $url;
?>
Explode will always work. However, if you want a neater way to do it you can do this:
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$newurl = substr_replace($url, "big", strrpos($url, '/') + 1, 0);
This will give your expected result: http://www.example.com/assets/images/temp/big10.jpg
There are quite a few methods to accomplish what you're wanting.
To me the easiest would be to use pathinfo to extract the filename, and then append your prefix to the basename.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$pathinfo = pathinfo($url);
var_dump($pathinfo['dirname'] . '/' . $prefix . $pathinfo['basename']);
Result: https://3v4l.org/3MkIG
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Object oriented approach: https://3v4l.org/aF5lf
class FileNamePrefixer extends SplFileInfo
{
public function addPrefix($prefix)
{
return $this->getPathInfo() . '/' . $prefix . $this->getBaseName();
}
}
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$fileInfo = new FileNamePrefixer($url);
var_dump($fileInfo->addPrefix('big'));
Another method is to use preg_replace to specify a pattern of words you want to replace.
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)$/', $prefix . '$1$2', $url);
var_dump($new_url);
The pattern ([\w|\s|-]+)(\.\w+)$ means; at the end of the string, look for a word (characters: a-z, A-Z, 0-9, _, space, and -), followed by a period, which is followed by another word and store them in variables $1 and $2.
Result: https://3v4l.org/6e8d7
string(51) "http://www.example.com/assets/images/temp/big10.jpg"
Note that if your URL will optionally contain fragments or a querystring, the preg_replace pattern above will not work. Instead you would need to account for them as optional like so:
$prefix = 'big';
$url = 'http://www.example.com/assets/images/temp/10.jpg?foo=bar&baz=foo#foobar';
$new_url = preg_replace('/([\w|\s|-]+)(\.\w+)(\?.+)?(#.+)?$/', $prefix . '$1$2$3$4', $url);
var_dump($new_url);
The pattern (\?.+)?(#.+)? means; optionally find ? followed by anything, and optionally find # followed by anything and store them in variables $3 and $4 with the original pattern.
Result: https://3v4l.org/uuYrO
string(74) "http://www.example.com/assets/images/temp/big10.jpg?foo=bar&baz=foo#foobar"

Remove last child page from URI

How can one dynamically find and remove the last child of a website path URI?
Code: $uri = $_SERVER["REQUEST_URI"];
Result: http://192.168.0.16/wordpress/blog/page-2/
Desired result: http://192.168.0.16/wordpress/blog/
Many thanks in advance!
you can use this and you can get your required output:
// implode string into array
$url = "http://192.168.0.16/wordpress/blog/page-2/";
//then remove character from right
$url = rtrim($url, '/');
// then explode
$url = explode('/', $url);
// remove the last element and return an array
json_encode(array_pop($url));
// implode again into string
echo implode('/', $url);
another approach is:
// implode string into array
$url = explode('/', 'http://192.168.0.16/wordpress/blog/page-2/');
//The array_filter() function filters the values of an array using a callback function.
$url = array_filter($url);
// remove the last element and return an array
array_pop($url);
// implode again into string
echo implode('/', $url);
$url = 'http://192.168.0.16/wordpress/blog/page-2/';
// trim any slashes at the end
$trim_url = rtrim($url,'/');
// explode with slash
$url_array = explode('/', $trim_url);
// remove last element
array_pop($url_array);
// implade with slash
echo $new_url = implode('/', $url_array);
Output:
http://192.168.0.16/wordpress/blog
The correct way would be to use parse_url() and dirname(), which will also support query params. You could explode $uri['path'] but its unnecessary in this case.
<?php
// explode the uri in its proper parts
$uri = parse_url('/wordpress/blog/page-2/?id=bla');
// remove last element
$path = dirname($uri['path']);
// incase you got query params, append them
if (!empty($uri['query'])) {
$path .= '?'.$uri['query'];
}
// string(22) "/wordpress/blog?id=bla"
var_dump($path);
See it working: https://3v4l.org/joJrF

Parsing url and routing issues

www.foo.com/Base/index.php/controller/method/
This is my url, I need to get only "controller/method" part out of it - is there any elegant way to achieve this?
parse_url($url, PHP_URL_PATH)
This would be great, but it returns the whole "Base/index.php/controller/method" part.
$url = "http://www.foo.com/Base/index.php/controller/method/";
$path = parse_url($url, PHP_URL_PATH);
$parts = explode("/", $path);
$index = array_search("index.php", $parts);
$controller = $parts[$index+1];
$method = $parts[$index+2];
You did not provide any additional information about url format. But as example, you may use regular expressions with preg_match():
$url = "http://www.foo.com/Base/index.php/controller/method/";
preg_match ("/^.*Base\/index.php\/([a-zA-Z0-9_]*)\/([a-zA-Z0-9_]*)\/?/", $url, $data);
$controller = $data[1];
$method = $data[2];

How to trim down a URL using regex in PHP?

I am struggling to finish this regex code in PHP. I want to trim down the following url which is held in variable $text so that it goes from:
http://www.site.net/showthread.php?tid=324&pid=...
to:
showthread.php?tid=324
Thank you kindly!
Why use a regex? The parse_url method should give you all you want: http://php.net/manual/en/function.parse-url.php
Edit: working example
$someurl = 'http://www.site.net/showthread.php?tid=324&pid=...';
$urlParts = parse_url($someurl, PHP_URL_PATH | PHP_URL_QUERY);
$params = parse_str($urlParts['query']);
unset($params['pid']);
$queryString = http_build_query($params);
$newUrl = $urlParts['path'] . '?' . $queryString;
Since $urlParts['path'] start with a / and you didn't want that, you could even use
$newUrl = substr($newUrl, 1);
and be done :) Does that help at all?
This should do it:
$url = 'http://www.site.net/showthread.php?tid=324&pid=...';
$pattern = "/showthread.php\?tid=[0-9]+/";
if (preg_match($pattern, $url, $match))
print_r($match);

Categories