Hi guys i m using this code to get the id on my url
$string = $url;
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);
$id = $matches[1][0];
this code works for urls like
http://mysite.com/page/1
http://mysite.com/page/somepage/2
http://mysite.com/page/3/?pag=1
i will have id = 1 / id = 2 / id = 3
but for a url like this
http://mysite.com/page/122-page-name/1
this returns id = 122
THe id i m try to get always will be the last part of the url or will have /?p= after
so the urls type i can have
http://mysite.com/page/1
http://mysite.com/page/some-page/2
http://mysite.com/page/12-some-name/3
http://mysite.com/page/some-page/4/?p=1
http://mysite.com/page/13-some-page/5/?p=2
id = 1 / id = 2 / id = 3 / id = 4 / id = 5
If your id will always be located at the end of your url, you could explode the contents of your url and take the last element of the resulting array. If it may include variables (like ?pag=1) you can add a validation after the explode to check for the variable.
$urlArray = explode('/', $url);
$page = end($urlArray);
if(strpos($page, 'pag')!==false){
//get the contents of the variable from the $page variable
//exploding the variable through the ? variable and getting
//the numeric characters at the end
}
I would favor URL parsing over trying to use a regex, especially if you have a wide variety of (valid) URLs to deal with.
end(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));
The array_filter deals with the trailng slash.
Since it's always at the end or has ?p=x after it you can do the following:
$params = explode('/', $_SERVER['REQUEST_URI']);
$c = count($params);
if (is_int($params[$c - 1])
$id = $params[$c - 1];
else
$id = $params[$c - 2];
Not a direct answer, more of a "how to work this out for yourself" answer :]
Place this code at the top of your page, before anything else (but after <?php)
foreach($_SERVER as $k => $v) {
echo $k.' = '.$v.'<br />';
}
exit;
Now load up each of the different URIs in a different tab and look at the results. You should be able to work out what you need to do.
Related
I am not very professional but
I have this PHP code :
$m = mysqli_query($dblink,"select * from bot where type='movie' and ID ='$wait'");
while($a = mysqli_fetch_array($m, MYSQLI_ASSOC)){
$ex = explode(",",$a["links"]);
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches);
$urls = $matches[0];
foreach($urls as $url){
$s=size($url);
}
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches2);
$urls2 = $matches2[0];
}
and I also have http://site1.com,http://site2.com,http://site3.com in my "links" column of database.
so here is my problem : the code only shows one of the sites.
I was wondering if the problem is with foreach or explode or non of them?
thank all of you in advance!
EDIT :
so I changed my code to this :
$ex = explode(",",$a["links"]);
$url=$a["links"];
foreach($ex as $url){
$s=size($url);
...
}
and it seems to be a problem with $url because when I use a custom url for example http://test.com instead of $url it works and shows me 3 links which is the number of links in my database with the url of http://test.com.
What am I doing wrong with $url ?
$ex = explode(",",$a["links"]);
Will return an array of values (links) as follows:
$ex[0] = 'http://site1.com'
$ex[1] = 'http://site2.com'
$ex[2] = 'http://site3.com'
And you are passing only the second position of the array (index = 1 => $ex[1]) to the next line
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches);
so, you can do this:
foreach($ex as $url) {
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $url, $matches);
}
to get the matches for each url in the links database column
I have a url like this
url:- url.php?gender=male&&grand=brand1&&id=$id
eg. $id may be 1, 100 ,23, 1000 any number
I am getting the url using
<?php echo $_SERVER['REQUEST_URI']; ?>
Is it possible to change the id and make the url like
url:- url.php?gender=gender&&brand=brand1&&id=$newId
where $newId can be any number except the one that is present in the url
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -2);
return $url;
}
this will do the job, pass your url and key you want to remove in this function
ex remove_querystring_var("url.php?gender=male&&grand=brand1&&id=$id","id"), it will remove id from your url
Get the id position and the remove the id using sub string.
$url = $_SERVER['REQUEST_URI'];
#Get id position and remove && by subtracting 2 from length
$pos = strrpos($url,'id') - 2;
$url = substr($url, 0, $Pos);
echo $url;
You could use $_SERVER['QUERY_STRING'] instead.
Moreover, if your 'id' value is not always at the end, getting a substr up to it wouldn't be very robust. Instead turn it into an associative array and fiddle with it.
For example, starting with /url.php?gender=male&grand=brand1&id=999&something=else
parse_str($_SERVER['QUERY_STRING'], $parsed);
unset($parsed['id']);
// there may be a better way to do this bit.
$new_args = [];
foreach($parsed as $key=>$val){
$new_args[] = "$key=$val";
}
$new_arg_str = join($new_args, '&');
$self = $_SERVER['PHP_SELF'];
$new_endpoint = "$self?$new_arg_str";
echo $new_endpoint;
result: /url.php?gender=male&grand=brand1&something=else
Bit more legible than regex as well.
Bear in mind if you're going to redirect (using header("Location: whatever") or otherwise), you'll need to be wary of redirect loops. An if statement could avoid that.
References:
http://php.net/manual/en/reserved.variables.server.php
http://php.net/manual/en/function.parse-str.php
http://php.net/manual/en/function.unset.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.join.php
My query generates a result set of UID values which looks like:
855FM21
855FM22
etc
I want to isolate the last number from the UID which it can be done by splitting the string.
How to split this string after the substring "FM"?
To split this string after the sub string "FM", use explode with delimiter as FM. Do like
$uid = "855FM22";
$split = explode("FM",$uid);
var_dump($split[1]);
You can use the explode() method.
<?php
$UID = "855FM21";
$stringParts = explode("FM", $UID);
$firstPart = $stringParts[0]; // 855
$secondPart = $stringParts[1]; // 21
?>
use explode function it returns array. to get the last index use echo $array[count($array) - 1];
<?php
$str = "123FM23";
$array = explode("FM",$str);
echo $array[count($array) - 1];
?>
For it,please use the explode function of php.
$UID = "855FM21";
$splitToArray = explode("FM",$UID);
print_r($splitToArray[1]);
Have you tried the explode function of php?
http://php.net/manual/en/function.explode.php
As a matter of best practice, never ask for more from your mysql query than you actually intend to use. The act of splitting the uid can be done in the query itself -- and that's where I'd probably do it.
SELECT SUBSTRING_INDEX(uid, 'FM', -1) AS last_number FROM `your_tablename`
If you need to explode, then be practice would indicate that the third parameter of explode() should set to 2. This way, the function doesn't waste any extra effort looking for more occurrences of FM.
echo explode('FM', $uid, 2)[1]; // 21
If you want to use php to isolate the trailing number in the uid, but don't want explode() for some reason, here are some wackier / less efficient techniques:
$uid = '855FM21';
echo strtok($uid, 'FM') ? strtok('FM') : ''; // 21
echo preg_replace('~.*FM~', '', $uid); // 21
echo ltrim(ltrim($uid, '0..9'), 'MF'); // 21
$uid = '123FM456';
$ArrUid = split( $uid, 'FM' );
if( count( $ArrUid ) > 1 ){
//is_numeric check ?!
$lastNumbers = $ArrUid[1];
}
else{
//no more numbers after FM
}
You can also use regular expressions to extract the last numbers!
a simple example
$uid = '1234FM56';
preg_match( '/[0-9]+fm([0-9]+)/i', $uid, $arr );
print_r($arr); //the number is on index 1 in $arr -> $arr[1]
I am parsing domains and running into a problem handling subdomains. If the domain is http://www.google.co.uk, I want to obtain the length of google which is 6.
I am using parse_url() to return the host in this case www.google.co.uk like so.
$url = 'http://www.google.co.uk';
$info = parse_url($url);
// remove www. and return google.co.uk
$new = str_replace('www.','',$info['host']);
$pieces = explode(".", $new);
$len = strlen($pieces[0]); // returns character length of google = 6
echo $len;
My code doesn't work if the domain contains a subdomain like http://test.google.co.uk: it returns a length of 4; I expect it to return a length of 6.
Any ideas?
Output is correct. when input is http://test.google.co.uk value of parse_url('http://test.google.co.uk')['host'] is http://test.google.co.uk. When you will exploce this string on dot first element of array will be test and its length is 4.
To get google instead of test you need to replace subdomain with nothing as you did in your first example or take the second element in exploded string. E.g:
$url = 'http://test.google.co.uk';
$info = parse_url($url);
$pieces = explode(".", $info['host']);
$len = strlen($pieces[1]); // returns character length of google = 6
echo $len;
There is not other way than collect and hardcode all known public 2-nd level zones (like co.uk, com.ua, co.tw and so on) and filter them in your code. Be aware to detect test.example.ua as test becouse both example.com.ua and example.ua are valid domains (which is not a case with uk zone).
Your code may look like this:
function mainDomainLength($fullDomain) {
//$fullDomain = 'DOMAIN.co.uk';
$zones = array('uk' => array('co'), 'ua' => array('com', 'org'), ...);
$domainArray = explode('.', $fullDomain);
if (count($domain) > 2 && isset($zones[$domain[count($domain)-1]])) {
if (isset($zones[$domain[count($domain)-1]][$domain[count($domain)-2]])) {
return strlen($domain[count($domain)-3]);
}
} else if (count($domain) > 1) {
return strlen($domain[1]);
} else {
return strlen($domain[0]);
}
}
EDIT: By the way! Look at Get the second level domain of an URL (java). As I can understand there is the answer you need (and url to special domains collection collected be Mozilla).
Is there a way in php to do a preg_match on a url like below
dynamic/dynamic/dev/new_mobile/lib
and it would only pull out dev/new_mobile, and the link also has the ability to be like this too
dynamic/dynamic/dynamic/tst/new_mobile/lib
In the above example it would only pull out tst/new_mobile. The key is it would grab the last two directories before lib. Any idea how this could be done?
Here's a regex that will get the part you want:
$url = 'dynamic/tst/new_mobile/lib/foo/bar';
if (preg_match('#^(?:.*?/)?([^/]+/[^/]+)/lib(?:/.+)?$#', $url, $matches)) {
$part = $matches[1];
var_dump($part); // "tst/new_mobile"
}
This will get the 2 directories before the lib directory allowing for any directories before and after. It will also match a couple of edge cases that you don't mention whether you need:
tst/new_mobile/lib/foo/bar
/tst/new_mobile/lib/foo/bar
just explode then reverse array, simple and easy to use.
$array_url = explode('/',$url);
$tmp_array_url = array_reverse($array_url);
then you can rebuild as you will, no need to wonder with how many dynamic parts come before.
echo $tmp_array_url[0]; // "lib";
echo $tmp_array_url[1]; // "new_mobile";
echo $tmp_array_url[2]; // "dev";
EDIT: since you got lib constant, just do something like this :
$the_two_before = "";
for($i = 0; $i < count($tmp_array_url); $i++){
if($tmp_array_url[$i] == "lib"){
$the_two_before = $tmp_array_url[$i+2]."/".$tmp_array_url[$i+1];
}
}