if I have this url: node/95/pdf/1. How will I able to get the numeric/value 1? Tried the parse_url but gave me the wrong output.
PS: the value 1 is just an example, the id is dynamic depends on what the user click.
I would use sscanf
Untested example:
list($node_id, $pdf_id) = sscanf($url, "node/%d/pdf/%d");
$node_id contains the node id, $pdf_id contains the pdf id. According to your comment: Yes, you can output it with e.g. echo $pdf_id;.
If you need them both in an array, you can remove the list() method, doing it like this:
$ids = sscanf($url, "node/%d/pdf/%d");.
This returns an array with both node and pdf id in $ids.
Finally, if you just need the pdf id, you could do
$id = sscanf($url, "node/95/pdf/%d");.
I just showed how to fetch both because I assumed you may need both numbers from your url.
Edit
seeing all the other answers after posting my solution, I am wondering why everyone is solving this with multiple functions when there is a function available that does exactly what he needs: parsing a string according to a format. This also leads to less sql-injection prone code IMHO. And it doesn't break something when the url gets extended or query strings are appended.
Edit 2
list($node_id, $sub, $sub_id) = sscanf($url, "node/%d/%[^/]/%d"); will get you the "pdf" and it's id separate instead of "node/%d/%s/%d". This is because char / is also matched by %s. Using %[^/] matches everything except the forward slash.
You can do this:
$id = end(explode('/', 'node/95/pdf/1'));
Example:
$arr = explode('/', 'node/95/pdf/1');
$id = end($arr);
echo $id; // 1
$url = "node/95/pdf/1";
// Find the last occurence of a slash, get everything after that.
$id = substr($url, strrpos($url, "/") + 1 );
Try with:
$input = 'node/95/pdf/1';
$parts = explode('/', $input);
$output = (int) $parts[3];
Related
sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);
I need to get the last three parts of a string (url). No need to pull the url from the browser as I already grab it from the database.
So, the string looks like: www.mysite.com/uploads/09/03/myimage.png
The part I'd like to extract from the string is "09/03/myimage.png"
<?php
$url="www.mysite.com/uploads/09/03/myimage.png";
$values=explode("/",$url); // this will split url string to array based on "/"char
$length=sizeof($values); //calculated array length
$lastthreeStringsCombined=$values[$length-3].'/'.$values[$length-2].'/'.$values[$length-1]; // formed new string by combining last 3 array elements
echo $lastthreeStringsCombined;
?>
Try this:
$lastThreeParts = implode('/', array_slice(explode('/', $url), -3, 3, true));
I'm assuming you want to pull out just the path part and ignore query parameters or hash values in the URL.
I would suggest using parse_url() (documented here: http://php.net/manual/en/function.parse-url.php) to pull out the path.
$url = 'www.mysite.com/uploads/09/03/myimage.png';
$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$output = array_slice($parts, -3, 3);
var_dump($output);
This will provide you with an array of the last 3 parts of the path and handles cases like query strings and hash values in the array, of course you will still need to do basic length validation to ensure this logic still holds.
Long time lurker first time poster here:
I have searched high and low and am trying to keep my php script somewhat the same as it is:
$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
however when I echo $url I need to:
Remove the string from www.example.com/?utm_source=etc
removing everything after /? on multiple file names like
www.example.com/page.htm/?utm_source=etc
www.example.com/page1.htm/?utm_source=etc
and so on
Keep the google custom search query string www.example.com/search.htm?q=term
Keep a couple other search string close the GSE string example
Ive seen some examples but none worked for me without making a ton of changes, surley there is a easier way.
Thanks in Advance
This will do the job for you. I used php regex and preg_replace() predefined function for it.
Regex (Fiddle Link)
/www(\.)[A-Za-z0-9]+\.\w+(\/)(\?)?((\w)+(\.)(\w)+)?((.)+)?/i
Php example
<?php
$input_line = 'www.example.com/?utm_source=etc'; //Input String
$replace_String = ''; //specify your replace string here
$regex = preg_replace("/www(\.)[A-Za-z0-9]+\.\w+(\/)(\?)?((\w)+(\.)(\w)+)?((.)+)?/i", $replace_String, $input_line);
print_r($regex); //this will print the output with replaced string
?>
You need to split url into different pieces and then put all of it back together - this is the only way.
So for example if your url is
$url = www.example.com/page1.htm/?utm_source=etc&some_key=some_key_value&someothekey=someotherid
$url_array = explode("?",$url);
$url_path = $url_array[0];
$url_params = explode("&",$url_array[1]);
$i = 0;
foreach($url_params as $url_param){ // Let's get specific url parameter and it's value
$i++;
$url_key = explode("=",$url_param)[0];
$url_value = explode("=",$url_param)[1];
$some_key = "some_key";
/*
* or use $i auto increment to find, relevant search parameter based on position e.g.
* if($i = 0){ // 0 is first etc.
* $some_key = $url_key;
* }
*/
// now that we have all keys - let's compare
if($url_key === $some_key){
$some_key_value .= $url_value; // Note the dot before ".=" so you can use it outside the loop, do the same if statements for any other keys you need
}
}
$new_url = $url_path."?".$some_key."=".$some_key_value;
I need to take a unique parameter from url generally appendened as last word of the url.
For example, I need to take 2220193 and 2220136 from the following urls:
"http://www.break.com/index/strange-sea-creature-retreats-into-ocean-floor-2220193"
"http://www.break.com/index/bully-picks-fight-with-sleeping-inmate-2220136"
Generally I use str_replace to remove the static parameter "http://www.break.com/index/", but I don't know how to delete the textual url and get only the number.
$id = substr($url, strrpos($url, '-') + 1);
Use explode on the url, this returns a string array. The last value in the string array should contain what you are looking for.
Given that $_SERVER['PATH_INFO'] would contain a url of the given format, you could use.
$url = $_SERVER['PATH_INFO'];
$urlParts = explode($url, '-');
echo end($urlParts);
Probably You could use preg_match PHP function
$outarr = explode('-',$inputstr);
$outnum = $outarr[count($outarr);
I'm trying to get a users ID from a string such as:
http://www.abcxyz.com/123456789/
To appear as 123456789 essentially stripping the info up to the first / and also removing the end /. I did have a look around on the net but there seems to be so many solutions but nothing answering both start and end.
Thanks :)
Update 1
The link can take two forms: mod_rewrite as above and also "http://www.abcxyz.com/profile?user_id=123456789"
I would use parse_url() to cleanly extract the path component from the URL:
$path = parse_URL("http://www.example.com/123456789/", PHP_URL_PATH);
and then split the path into its elements using explode():
$path = trim($path, "/"); // Remove starting and trailing slashes
$path_exploded = explode("/", $path);
and then output the first component of the path:
echo $path_exploded[0]; // Will output 123456789
this method will work in edge cases like
http://www.example.com/123456789?test
http://www.example.com//123456789
www.example.com/123456789/abcdef
and even
/123456789/abcdef
$string = 'http://www.abcxyz.com/123456789/';
$parts = array_filter(explode('/', $string));
$id = array_pop($parts);
If the ID always is the last member of the URL
$url="http://www.abcxyz.com/123456789/";
$id=preg_replace(",.*/([0-9]+)/$,","\\1",$url);
echo $id;
If there is no other numbers in the URL, you can also do
echo filter_var('http://www.abcxyz.com/123456789/', FILTER_SANITIZE_NUMBER_INT);
to strip out everything that is not a digit.
That might be somewhat quicker than using the parse_url+parse_str combination.
If your domain does not contain any numbers, you can handle both situations (with or without user_id) using:
<?php
$string1 = 'http://www.abcxyz.com/123456789/';
$string2 = 'http://www.abcxyz.com/profile?user_id=123456789';
preg_match('/[0-9]+/',$string1,$matches);
print_r($matches[0]);
preg_match('/[0-9]+/',$string2,$matches);
print_r($matches[0]);
?>