remove a part of url using php - php

I have this url :
http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg
and need to convert to :(remove all url before 1)
1/images/hd-wallpaper-40.jpg
EDIT:
http://localhost/cms/uploads/files/ is dynamic So Maybe : http://localhost/uploads/files/
how do can I convert this url using php?

I don't know the rules/conditions you need but this is a way:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
echo str_replace('/cms/uploads/files/', '', $url['path']);
UPDATE:
If imagesis static:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
preg_match('/[0-99999]\/.*/', $url['path'], $matches);
echo $matches[0];

You can use parse_url function to get whatevers after the host (in this case localhost) and then explode the path, slice an array and implode it back:
$str = "http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg";
$parsed_url = parse_url($str);
echo implode("/", array_slice(explode("/", $parsed_url['path']),4));

a simple solution may be;
$basepath = 'http://localhost/cms/uploads/files/';
$url = 'http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg';
if (strncmp($basepath, $url, strlen($basepath)) == 0 ) {
$result = substr($url, strlen($basepath));
} else {
$result = false;
}
echo $result;

Try this, dynamic content with '/1/' will work perfectly
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$pos = strpos($str,'1'); //position of first '1' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos,($len-$pos)); //substring from '1' onwards
There are few drawbacks too. If the '1' occurres before , i mean url = "http://localhost/cms1/uploads/files/1/images, it will give wrong result.
If you use dynamic author id, instead of 1, save author id as a variable and insert in strpos(). The below one will be more accurate and you can use dynamic authorID too.
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$authid = 1; //author id
$searchstring = '/'.$authid.'/'; // create a search string '/1/'
$pos = strpos($str,$searchstring); //position of first '/1/' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos+1,($len-$pos)); //substring from '1' onwards

Related

Preg_match url to get id numbers

I tried preg_match and explode and everything but doesnt get good solution for getting id numbers in url.
URL-s
$a = strtolower('<iframe src="//LearningApps.org/watch?app=1250652" style="border:0px;width:100%;height:500px" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>');
$b = strtolower('http://LearningApps.org/view1250652');
$c = strtolower('LearningApps.org/view1250652');
$d = strtolower('LearningApps.org/watch?app=1250652');
$e = strtolower('LearningApps.org');
$f = strtolower('http://learningapps.org/339473');
And i tried:
$match = '/[0-9]{7}/';
preg_match($match, $end, $matches);
print_R($matches);
But id lenght can change, so that isnt good solution for me.
As developer of the named service learningapps.org I can provide you with our own PHP function to parse URLs to get the ID:
function getLearningAppID($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $params );
$ID = null;
$GUID = "";
if(isset($params["v"])) $GUID = $params["v"];
if(isset($params["id"])) $GUID = $params["id"];
if($GUID == ""){
// try AppID
if(preg_match("#learningapps.org/(?:view)?(\d+)#i",$url,$matches)){
$ID = $matches[1];
}else{
if(isset($params["app"])) $ID = $params["app"];
}
}
// now you have either a value in $ID (public app) or $GUID (private app)
...
}
You can also always contact us directly by mail, we are happy to hear about development projects based on learningapps.org :-)
If you are trying to get only the digits, you can use regex.
preg_match("/([0-9]{5,})/", $input_line, $output_array);
Check the code
Or (but case if you have a string with some other numbers the regex below will not work correctly)
preg_replace("/\D/", "", $input_lines);
Check the code
This will work accurately if the iframe style values are same across your entire code:
$c = strtolower('<iframe src="//LearningApps.org/watch?app=1250652" style="border:0px;width:100%;height:500px" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>');
$numbers = intval(preg_replace('/[^0-9]+/', '', substr($c, 0, -100)), 10);
echo $numbers;

Using preg_replace to get id

how to get id url with preg_replace.
this is the link:
http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id how do I get the id? in the case would be: 5b87f8eaa7c20f79c3257eb3ec0a35e0
In this case I recommend not to use preg_match (preg_replace would be used to replace something.
Simply use
$array = explode('/',$_SERVER['REQUEST_URI']);
$id = $array[1];
If you must use preg_match:
$array = array();
preg_match('#^/photo/([0-9a-f]{32})/id$#',$_SERVER['REQUEST_URI'],$array);
$id = $array[1];
You can do this easily using strripos to find the last / in the URL.
$url = $_SERVER['REQUEST_URI'];
if (($pos = strripos($url, '/')) !== false) {
$id = substr($url, $pos + 1);
}
else {
trigger_error('You must supply a valid photo ID');
}
If you would like to just extract that id string, you can use:
$id_url = "http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id";
$pattern = "/photo\/([a-zA-Z0-9]*)/";
preg_match($pattern, $id_url, $output_array);
echo $output_array[1];
Or, to make the replacement:
$id_url = "http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id";
$pattern = "/photo\/([a-zA-Z0-9]*)/";
$replacement = "your replacement";
$replaced_url = preg_replace($pattern, $replacement, $id_url);
echo $replaced_url;
PHP Live Regex - a useful tool for testing your patterns

How to remove last element in php [duplicate]

This question already has answers here:
Strip off specific parameter from URL's querystring
(22 answers)
Closed 8 years ago.
I have to remove the last element in a string. I used rtrim in php but it is not working.
This is the string:
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC
I need to remove "&make_order=ASC"
Can anyone help me?
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));
Edit:
$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
// ^
// |_ replace , with .
trim should work:
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");
There's no guarantee that make_order will be at the end of the query string - or exist at all. To remove the field properly, you'd have to use something like this:
$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
// break down the URL into a path and query string
$parsed = parse_url($url);
// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);
// remove the unwanted field
unset($qs['make_order']);
// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
$rebuilt .= '?' . http_build_query($qs);
}
echo $rebuilt;
$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo str_replace("&make_order=ASC","",$actual_link);
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$args = array_pop(explode($string, "&"));
$string = implode("&", $args);
There are a bunch of ways. The easiest might be:
$i=strrpos($text,'&');
$newstring=substr($text,0,$i);
$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");
if &make_order=ASC is always going to be at the end, you can use strstr() to do this
$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);
Remove desired key from url.
Use:
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');
Output :
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100
Code:
function remove_key_from_url($url, $key) {
if (strpos($url, '?') === false) return $url;
list($left, $right) = explode('?', $url, 2);
parse_str($right, $get);
if (isset($get[$key])) unset($get[$key]);
return $left . '?' . http_build_query($get);
}

Using an expression to remove part of a string

This is probably simple however I am not the best with expressions..
I am trying to get the following string from..
http://www.yoursite.com/offers/838?&SITEID=2172
to this.. using an expression that will remove the ?&SITEID and the dynamic id which will vary
http://www.yoursite.com/offers/838
Can anyone suggest the best/simplest method to do this?
Check this function:
$str = 'http://www.yoursite.com/offers/838?&SITEID=2172';
function remove_query_arg($var, $url = NULL){
if(!$url){
$url = $_SERVER['REQUEST_URI'];
}
$parsed_url = parse_url($url);
$query_vars = explode('&', $parsed_url['query']);
foreach($query_vars as $key => $value){
$query_vars[$key] = explode('=', $query_vars[$key]);
$query_variables[$query_vars[$key][0]] = $query_vars[$key][1];
}
if(is_array($var)){
foreach($var as $value){
unset($query_variables[$value]);
}
}
elseif(is_string($var)){
unset($query_variables[$var]);
}
$query_vars = array();
foreach($query_variables as $key => $value){
$query_vars[] = $key.($value !== NULL || !empty($value) ? '='.$value : '');
}
$query_str = '';
$query_str = implode('&',$query_vars);
return (isset($parsed_url['scheme']) && !empty($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '').$parsed_url['host'].(isset($parsed_url['path']) && !empty($parsed_url['path']) ? $parsed_url['path'] : '').(!empty($query_str) ? '?'.$query_str : '');
}
echo remove_query_arg('SITEID', $str);
This is a URL, so parse it as one, with parse_url().
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$parts = parse_url($url);
$url = $parts["scheme"] . "://" . $parts["host"] . $parts["path"];
Using explode function returns an array
$url=http://www.yoursite.com/offers/838?&SITEID=2172
$result=explode('?',$url)
print_r($result);
output
array
{
[0]=>http://www.yoursite.com/offers/838
[1]=>?&SITEID=2172
}
A valid URL only has one ? so you can just use explode to break it into 2 parts
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
list($path, $query) = explode("?", $url, "2");
var_dump($path);
Output
string 'http://www.yoursite.com/offers/838' (length=34)
$url = "http://www.yoursite.com/offers/838?&SITEID=2172";
$str = substr($url, strpos($url, 0, "?&SITEID"));
// $str results in "http://www.yoursite.com/offers/838"
If you want to keep the part before the ? you can search
^(.+?)(\?&SITEID|$)
and replace with
$1
You search non greedily from the beginning of the line ^ to the first ?&SITEID and leave out the rest. If no ?&SITEID is found you get the entire line by arriving at the end of the string with $
| is the OR operator that tells the regex "Stop at the first ?&SITEID or at the end of the string"
EDIT:
After the comment where you explain your need to keep the rest of the querystring I suggest you a different approach: find
&?SITEID=[^&\s]+
being
&? an optional & at the beginning of the string
SITEID= the string you are looking for followed by
[^&\s]+ any number of non&, nonspace character
and remove it from the string. However, being this the case, I'd go with a non-regex, url-specific approach like suggested in the other answers.

Grab variable from php URL string

What's the easiest way to grab a 6-character id from a string?
The id will always be after www.twitpic.com/ and will always be 6 characters.
e.g., $string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = 'f1462i';
Thanks.
Here you go. Complete working code without regex :
<?php
$string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = substr($string, strpos($string, 'http://www.twitpic.com/')+23, 6);
echo $id; //output: f1462i
?>
$string = "http://www.twitpic.com/f1462i" ;
$id = substr($string,strpos($string, 'twitpic.com')+strlen('twitpic.com')+1,6) ;
echo $id ;
preg_match("#twitpic\.com/(\w{6})#", "The url is http://www.twitpic.com/f1462i. Enjoy.", $m);
$id = $m[1];

Categories