I have a string that looks like this, like a URL that has parameters.
folder/tested/file.js?p1=v1&p2=v2
How can I manipulate this string so as to remove all params, so that it ends up looking like this
folder/tested/file.js
Check out parse_url() - http://php.net/function.parse-url
$path = parse_url($url, PHP_URL_PATH);
$array = explode("?", "folder/tested/file.js?p1=v1&p2=v2");
$array[0];
There's no need for the explode workaround in this case:
$path = strtok($url, "?");
Here is another method that is somewhat 'dirty':
$tmp = 'folder/tested/file.js?p1=v1&p2=v2';
$pos = strpos($tmp, '?');
$url = substr($tmp, 0, $pos);
Try splitting by a '/' then by a '?' into two parts, and just taking what you need from both operations:
http://php.net/function.explode
Related
Please help me to create regex for replace a string like:
/technic/k-700/?type=repair
to a string like
/repair/k-700/
Instead of k-700 can be any another combination (between / ) and instead of repair can be only kit.
I need pattern and replacement, please. It's so hard for me.
My result not working for Wordpress:
$pattern = '/technic/([0-9a-zA-Z-]+)/?type=$matches[1]';
$replacement = '/?/([0-9a-z-]+)/';
You can try something like this:
$test = preg_replace(
'~/\w+/([\w-]+)/\?type=(\w+)~i',
'/$2/$1/',
'/technic/k-700/?type=repair'
);
var_dump($test);
The result will be:
string(14) "/repair/k-700/"
You don't need regex, you can do it simply by using explode():
$str = '/technic/k-700/?type=repair';
$first = explode('/', explode('?', $str)[0]);
$second = explode('=', explode('?', $str)[1]);
$first[1] = $second[1];
echo $new = implode("/",$first);
//output: /repair/k-700/
For the sake of completeness or if you need to access the url parts later.
Here's a solution using parse_url and parse_str
$str = '/technic/k-700/?type=repair';
$url = parse_url($str);
$bits = explode('/',trim($url['path'],'/'));
parse_str($url['query']);
print '/' . $type . '/' . $bits[1] . '/' ;
Which will output
/repair/k-700/
$url = explode('/', $articleimage);
$articleurl = array_pop($url);
I have used the above method to get the last part of a URL.Its working.But I want to remove the last part from the URL and display the remaining part.Please help me.Here I am mentioning the example URL.
http://www.brightknowledge.org/knowledge-bank/media/studying-media/student-media/image_rhcol_thin
Try this:
$url = explode('/', 'http://www.brightknowledge.org/knowledge-bank/media/studying-media/student-media/image_rhcol_thin');
array_pop($url);
echo implode('/', $url);
There is no need to use explode, implode, and array_pop.
Just use dirname($path). It's a lot more efficient and cleaner code.
Use the following string manipulation from PHP
$url_without_last_part = substr($articleimage, 0, strrpos($articleimage, "/"));
For Laravel
dirname(url()->current())
In url()->current() -> you will get current URL.
In dirname -> You will get parent directory.
In Core PHP:
dirname($currentURL)
after the array_pop you can do
$url2=implode("/",$url)
to get the url in a string
Change this:
$articleurl = array_pop($url);
Into this:
$articleurl = end($url);
$articleurl will then hold the last array key.
Missed the part where you want to remove the value, you can use the function key() to get the key and then remove the value using that key
$array_key = key($articleurl);
unset(url[$array_key])
Pretty simple solution add in the end of your code
$url = implode('/', $url);
echo $url;
Notice that array_pop use reference argument passing so array will be modifed implode() function does the opposite to explode function and connects array elements by first argument(glue) and returns the string.
It looks like this may be what you are looking for. Instead of exploding and imploding, you can use the parsing functions which are designed to handle exactly this kind of URL manipulation.
$url = parse_url( $url_string );
$result =
$url['scheme']
. "://"
. $url['host']
. pathinfo($url['path'], PATHINFO_DIRNAME );
Here's the simple way to achieve
str_replace(basename($articleimage), '', $articleimage);
For the one-liners:
$url = implode('/', array_splice( explode('/', $articleimage), 0, -1 ) );
$url[''] and enter the appropriate number
I need a regex string to extract parameters from different types of url, for example using $_SERVER["REQUEST_URI"]:
string 1: "/news/page/4" or string 2: "/news/weekly/page/4"
I need to extract the string without last /page/[ID], I mean only /news/page or /news/weekly/, etc.
How can I do it with preg_replace?
Thank you.
You can use explode() instead of regular expressions:
$delimiter = '/';
$parts = explode($delimiter, $_SERVER["REQUEST_URI"]);
$whatINeed = $parts[0] . $delimiter . $parts[1];
regexp solution:
echo preg_replace('/^([\w\W]*)\/page\/\d*/','$1','/news/weekly/page/4');
outputs:
/news/weekly
but you should use explode solution:
$parts = explode('/', $_SERVER["REQUEST_URI"]);
$url = $parts[0].'/'.$parts[1];
You should be able to use: [A-Za-z/]+
But it will be slower then just using substr. EDIT: not substr, but explode.
Try:
$foo = explode('/', $_SERVER["REQUEST_URI"]);
$resultant_url = $foo[0].'/'.$foo[1];
If I have a stored input string that looks like this
http://site.com/param1/value1
how can php extract value1?
I know how to extract parameters that look like this
http://site.com?param1=value1
but it doesn't work for the format I'm asking about.
Generally you could parse url with parse_url and then explode path by / , and than read second value in array.
You can use a simple string function combination:
$str = "http://site.com/param1/value1";
$tail = substr($str, strrpos($str, "/") + 1);
Or if it's not sure if there is a / somewhere in the string:
preg_match("#/(\w+)$#", $string, $match);
$tail = $match[1];
For the microoptimizers: this too will generally be faster as the array-explode() workaround.
Fast & Easy:
$url = "http://site.com/param1/value1";
$split_url = explode("/", $url);
$value = $split_url[3];
Looking at some php.net manuals you can easily find this function, that totaly fits your needs
strchr
$url = 'http://example.com/param1/value1';
list($param1, $value1) = array_slice(explode('/', $url), -2, 2);
This will give you param1 and value1 from the example stored in the variables $param1 and $value1.
Look up parse_URL that's the function you want
I would suggest a combination of Trickers and Toby Allens solution
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));
$value = $segments[2];
If you have multiple key-value-paris you can ensure with trim(), that the key is always even and the value always odd
$count = count($segments);
$result = array();
for ($i = 0; $i < $count; $i += 2) {
$result[$segments[$i]] = $segments[$i+1];
}
string '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg' (length=85)
what i need is just
http://localhost/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg
what is the best way doing it ? i mean useing strlen ? substr_replace ? substr ? im a bit confused what is the best way doing this? becouse there is many ways to do this.
edit* there is no newbie tag :|
// get from database red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg
$image_path = $this->data['products'][0]['image_small'];
$exploded = end(explode('/', $image_path));
$myurl = DOMAIN;
$myfullurl = $myurl."/storage/".$exploded;
// it works!, but let see the comments maybe there is a better way :)
Here is how you can get the image part:
$str = '/home/adam/Projects/red/storag/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
$exploded = end(explode('/', $str));
echo $exploded;
Result:
22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg
Now you can concatenate it with whatever eg:
$new_str = 'http://localhost/storage/' . $exploded;
echo $new_str;
Result:
http://localhost/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg
And It is most likely you want to concatenate the image path with your document root which you do like this:
$img_path = $_SERVER['DOCUMENT_ROOT'] . $exploded;
The idea is that you explode the string with explode function by specifying / as delimiter. This gives you array, now you use the end function to get the ending part of the array which is your image actually.
If the path prefix represents your document root path, then you can do this to strip it:
$path = '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
$_SERVER['DOCUMENT_ROOT'] = '/home/adam/Projects/red/';
if (substr($path, 0, strlen($_SERVER['DOCUMENT_ROOT'])) === $_SERVER['DOCUMENT_ROOT']) {
$uriPath = substr($path, strlen(rtrim($_SERVER['DOCUMENT_ROOT'], '/')));
echo $uriPath;
}
I suggest you check if the string contains /home/adam/Projects/red, and if it does, you use substr to get the part after it, and you glue it with http://localost.
$path = '/home/adam/Projects/red/storage/*snip*.jpg';
$basePath = "/home/adam/Projects/red";
if (strpos($path, $path) !== false)
$url = 'http://localhost' . substr($path, strlen($basePath));
This one's pretty much the easiest
str_replace(
"/home/adam/Projects/red",
"http://localhost",
"/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg"
);
$string = '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
str_replace('/home/adam/Projects/red', 'http://localost', $string)