I am going to make a URL checking system.
I have this URL
https://lasvegas.craigslist.org/mob/6169799901.html
Now I want to make this URL like this
https://lasvegas.craigslist.org/search/mob?query=6169799901
how can I do it using PHP?
Since I ended up (maybe?) solving it anyways, here's one method using URL/path parsing:
$url = 'https://lasvegas.craigslist.org/mob/6169799901.html';
$parsed = parse_url($url);
$basepath = pathinfo($parsed['path']);
echo $parsed['scheme'].
"://".
$parsed['host'].
"/search".
$basepath['dirname'].
"?query=".
$basepath['filename'];
Formatted for readability.
https://3v4l.org/E6Y54
Try this
$url = "https://lasvegas.craigslist.org/mob/6169799901.html";
$id = substr($url, strrpos($url, '/') + 1);
$id = str_replace(".html","",$id);
$result = "https://lasvegas.craigslist.org/search/mob?query=".$id;
echo $result;
Related
I'm trying to check the string after the last trailing slash in my URL.
My code is as follows:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$data = substr($url, strrpos($url, '/') + 1);
if($data == "dashboard") {
require_once VIEW_ROOT . '/cp/dashboard_view.php';
} else {
echo $data;
}
Once I go to http://MYURL/dashboard/in it should show in as the $data. Instead it gives me a 500 error.
You can simply use explode() function to break the string... .Or else $_SERVER[REQUEST_URI] shall give you the data after the host name...
But for the data after the last '/' explode function will work the best..
This will work.
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$x = explode('/',$url);
$data = $x[sizeof($x)-1];
echo $data;
You should try :
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
You need to join
http:// string with $_SERVER[HTTP_HOST] and then $_SERVER[REQUEST_URI] using .(dot).
I have "/foo/bar/url/" coming straight after my domain name.
What I want is to find penultimate slash symbol in my string and replace it with slash symbol + hashtag. Like so: from / to /# (The problem is not how to get URL, but how to handle it)
How this could be achieved? What is the best practice for doing stuff like that?
At the moment I'm pretty sure that I should use str_replace();
UPD. I think preg_replace() would be suitable for my case. But then there is another problem: what should regexp look like in order to make my issue solved?
P.S. Just in a case I'm using SilverStripe framework (v3.1.12)
$url = '/foo/bar/url/';
if (false !== $last = strrpos($url, '/')) {
if (false !== $penultimate = strrpos($url, '/', $last - strlen($url) - 1)) {
$url = substr_replace($url, '/#', $penultimate, 1);
}
}
echo $url;
This will output
/foo/bar/#url/
If you want to strip the last /:
echo rtrim($url, '/'); // print /foo/bar/#url
Here is a method that would function. There are probably cleaner ways.
// Let's assume you already have $url_string populated
$url_string = "http://whatever.com/foo/bar/url/";
$url_explode = explode("\\",$url_string);
$portion_count = count($url_explode);
$affected_portion = $portion_count - 2; // Minus two because array index starts at 0 and also we want the second to last occurence
$i = 0;
$output = "";
foreach ($url_explode as $portion){
$output.=$portion;
if ($i == $affected_portion){
$output.= "#";
}
$i++;
}
$new_url = $output;
Assuming you now have
$url = $this->Link(); // e.g. /foo/bar/my-urlsegment
You can combine it like
$handledUrl = $this->ParentID
? $this->Parent()->Link() + '#' + $this->URLSegment
: $this->Link();
where $this->Parent()->Link() is e.g. /foo/bar and $this->URLSegment is my-urlsegment
$this->ParentID also checks if we have a parent page or are on the top level of SiteTree
I might be tooooo late for answering this question but I thought this might help you. You can simply use preg_replace like as
$url = '/foo/bar/url/';
echo preg_replace('~(\/)(\w+)\/$~',"$1#$2",$url);
Output:
/foo/bar/#url
In my case this solved my problem:
$url = $this->Link();
$url = rtrim($url, '/');
$url = substr_replace($url, '#', strrpos($url, '/') + 1, 0);
I'm trying to change a value in a string that's holding my current URL. I'm trying to get something like
http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory
to look like
http://myurl.com/test/end.php?req=&srclang=english&destlang=english&service=MyMemory
replacing begin.php for end.php.
I need the end.php to be stored in a variable so it can change, but begin.php can be a static string.
I tried this, but it didn't work:
$endURL = 'end.php';
$beginURL = 'begin.php';
$newURL = str_ireplace($beginURL,$endURL,$url);
EDIT:
Also, if I wanted to replace
http://myurl.com/begin.php?req=&srclang=english&destlang=english&service=MyMemory
with
http://newsite.com/end.php?req=&srclang=english&destlang=english&service=MyMemory
then how would I go about doing that?
Assuming that you want to replace the script filename of the url, you can use something like this :
<?php
$endURL = 'end.php';
$url ="http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory";
$pattern = '/(.+)\/([^?\/]+)\?(.+)/';
$replacement = '${1}/'.$endURL.'?${3}';
$newURL = preg_replace($pattern , $replacement, $url);
echo "url : $url <br>";
echo "newURL : $newURL <br>";
?>
How do you want them to get to end.php from beigin.php? Seems like you can just to a FORM submit to end.php and pass in the variables via POST or GET variables.
The only way to change what page (end.php, begin.php) a user is on is to link them to another page from that page, this requires a page refresh.
I recently made a PHP-file for this, it ended up looking like this:
$vars = $_SERVER["QUERY_STRING"];
$filename = $_SERVER["PHP_SELF"];
$filename = substr($filename, 4);
// for me substr removed 'abc/' in the beginning of the string, you can of course adjust this variable, this is the "end.php"-variable for you.
if (strlen($vars) > 0) $vars = '?' . $vars;
$resultURL = "http://somewhere.com" . $filename . $vars;
URL = http://company.website.com/pages/users/add/
How do i find the subdomain from this via PHP
Such that $subdomain = 'company'
And $url = '/pages/users/add/'
You'll want to take a look at PHP's parse_url. This will give you the basic components of the URL which will make it easier to parse out the rest of your requirements (the subdomain)
$url = 'http://company.website.com/pages/users/add/';
$url_parsed = parse_url($url);
$path = $url_parsed['path']; // "pages/users/add/"
And then a simple regex* to parse $url_parsed['host'] for subdomains:
$subdomain = preg_match("/(?:(.+)\.)?[^\.]+\.[^\.]+/i", $url_parsed['host');
// yields array("company.website.com", "company")
* I tested the regex in JavaScript, so you may need to tweak it a little.
Or to avoid the regex:
$sections = explode('.', $url_parsed["host"]);
$subdomain = $sections[0];
I use $_SERVER['QUERY_STRING'] to get the query sting.
A example would be a=123&b=456&c=789
How could I remove the b value from the query string to obtain a=123&c=789 where b can be any value of any length and is alpha numeric.
Any ideas appreciated, thanks.
A solution using url parsing:
parse_str($_SERVER['QUERY_STRING'], $result_array);
unset($result_array['b']);
$_SERVER['QUERY_STRING'] = http_build_query($result_array);
The value is going to be $_GET['b'].
How about:
str_replace('&b='.$_GET['b'], '', $_SERVER['QUERY_STRING']);
you can use this function:
function Remove_QS_Key($url, $key) {
$url = preg_replace('/(?:&|(\?))'.$key.'=[^&]*(?(1)&|)?/i', "$1", $url);
return $url;
}
to remove any key you want, e.g.
echo Remove_QS_Key("http://domain.com/?a=b&ref=dusername&c=d&e=f&g=h", "ref");
result
http://www.domain.com/?a=b&c=d&e=f&g=h
Try this:
$query_new = preg_replace('/(^|&)b=[^&]*/', '', $query);
All the answers look good, but it will be more flexible if you do:
// Make a copy of $_GET to keep the original data
$getCopy = $_GET;
unset($getCopy['b']); // or whatever var you want to take out
// This is your cleaned array
var_dump($getCopy);
// If you need the URL-encoded string, just use http_build_query()
$encodedString = http_build_query($getCopy);
You simply make a variable using $_GET and exclude b query string in build process:
$query_string_new = 'a=' . urlencode($_GET['a']) . '&c=' . urlencode($_GET['c']);
The $query_string_new should now contain a=123&c=789
Pear already has a class(Net_URL2) that handles URL parsing/building:
Install via Composer: https://packagist.org/packages/pear/net_url2
Install as include: https://github.com/pear/Net_URL2/blob/master/Net/URL2.php
Example code:
$url = new Net_URL2('http://www.example.com/?one=1');
$url->setQueryVariable('two', 2);
echo $url; // http://www.example.com/?one=1&two=2
Here is a function to replace a query parameter: (like example.com?a=1&b=2 -> example.com?a=5&b=2)
function replace_qs_key($key, $value) {
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$current_url_without_qs = strtok($current_url, '?');
parse_str($_SERVER['QUERY_STRING'], $query_params);
$query_params['page'] = $value;
$_SERVER['QUERY_STRING'] = http_build_query($query_params);
$new_url = $current_url_without_qs .'?'. $_SERVER['QUERY_STRING'];
return $new_url;
}