i have a link with the following (varying) structure:
http://website.com/category/product/abc12345
the category- and the productname vary concerning their length, but the id (abc12345) is always located after the last "/" and is about 6-8 chars long.
i tried to extract the link with the following code:
preg_split('/[/]/', $val, $arr);
$narr[] = end($arr);
with val being the link and arr being the array, the result should be pasted in.
narr is the array i want to save to a file later, so it doesn't really matter here. unfortunately, my results are always empty when i try it this way.
I would go for:
$urlParts = parse_url($myUrl);
$parts = explode('/', $urlParts['path']);
$productId = array_pop($parts);
That way, you have no problems with anchors (#content) or query parameters (?id=123)
I'd use preg_match:
if (preg_match('#.*/(.*)#', $val, $match)) {
$result = $match[1];
}
You could also use something as simple as strrpos and substr:
$result = substr($val, strrpos($val, '/') + 1);
Under the following conditions:
The product (abc12345) is always at the end of the url
No querystrings/params
Try the following regular expression:
preg_match('/\/([\w]+)\/?$/', $val, $arr);
$product = $arr[1];
Related
I have below URL in my code and i want to split it and get the number from it
For example from the below URL need to fetch 123456
https://review-test.com/#/c/123456/
I have tried this and it is not working
$completeURL = https://review-test.com/#/c/123456/ ;
list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
Use parse_url
It's specifically made for this sort of thing.
You can do this without using regex also -
$completeURL = 'https://review-test.com/#/c/123456/' ;
list($url, $number) = explode('#c', str_replace('/', '', $completeURL));
echo $number;
If you wan to get the /c/123456/ params you will need to execute the following:
$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
The PHP_URL_FRAGMENT will return a component of the url after #
After parse_url you will end up with a string like this: '/c/123456/'
The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted
In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.
Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)
You should try this: basename
basename — Returns trailing name component of path
<?php
echo basename("https://review-test.com/#/c/123456/");
?>
Demo : http://codepad.org/9Ah83qaP
Subsequently you can directly take from pure regex to fetch numbers from string,
preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
Working demo
Simply:
$tmp = explode( '/', $completeUrl).end();
It will explode the string by '/' and take the last element
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.
An approach could be to
Capture the first part as a group (.+\/)
Then capture your number as a group (\d+)
Followed by a forward slash at the end of the line \/$/
This will take the last number from the url followed by a forward slash.
Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.
$completeURL = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;
Substr PHP
I have a string like http://domain.sf/app_local.php/foo/bar/33.
The last characters are the id of an element. Its length could be more than one, so I can not use:
substr($dynamicstring, -1);
In this case, it must be:
substr($dynamicstring, -2);
How can I get the characters after "/bar/" on the string without depending on the length?
To ensure you are getting an immediate section after the bar, use regular expressions:
preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33
You can use explode(), like this:
$id = explode('/',$var);
And take the element where you had the id.
You could use explode('/', $dynamicstring) to split the string into an array of the strings inbetween each /. Then you could use end() on the result of this to get the last part.
$id = end(explode('/', $dynamicstring));
Try this:
$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';
// split your string into an array with /
$parts = explode('/', $dynamicstring);
// move the array pointer to the end
end($parts);
// return the current position/value of the $parts array
$id = current($parts);
// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);
echo $id;
// $id => 33
Test it yourself here.
You can use a regular expression to do it:
$dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
echo $m[1];
}
I tested it out myself before answering. Other answers are reasonable too, but this will work according to your need...
<?php
$url = "http://domain.sf/app_local.php/foo/bar/33";
$id = substr($url, strpos($url, "/bar/") + 5);
echo $id;
Please find the below answer.
$str = "http://domain.sf/app_local.php/foo/bar/33";
$splitArr = explode('/', explode('//', $str)[1]);
var_dump($splitArr[count($splitArr)-1]);
To create an array from a string and get an element you need to do this:
$string = "1/2";
$array = explode("/", $string);
$elem = $array[0];
A little trick lets you use the strstr() and provides the same result as both lines above.
$elem = strstr($string, "/", true);
The issue is..
What if you want to return after the "/" instead of before it, but without the "/" prepended
If the "/" does not exist in the array, false is returned
strstr() is not the answer. Is there another method or syntax to get the string before the "/" in one line either by doing an array operation or some string operation?
You can do it like this in php 5.4 +
$string = "1/2";
$first = explode("/", $string)[0];
Eval.in example
You can use substr():
$after = substr($string, strpos($string, '/')+1);
the +1 makes it skip past the /.
I have this code here:
$imagePreFix = substr($fileinfo['basename'], strpos($fileinfo['basename'], "_") +1);
this gets me everything after the underscore, but I am looking to get everything before the underscore, how would I adjust this code to get everything before the underscore?
$fileinfo['basename'] is equal to 'feature_00'
Thanks
You should simple use:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
I don't see any reason to use explode and create extra array just to get first element.
You can also use (in PHP 5.3+):
$imagePreFix = strstr($fileinfo['basename'], '_', true);
If you are completely sure that there always be at least one underscore, and you are interested in first one:
$str = $fileinfo['basename'];
$tmp = explode('_', $str);
$res = $tmp[0];
Other way to do this:
$str = "this_is_many_underscores_example";
$matches = array();
preg_match('/^[a-zA-Z0-9]+/', $str, $matches);
print_r($matches[0]); //will produce "this"
(probably regexp pattern will need adjustments, but for purpose of this example it works just fine).
I think the easiest way to do this is to use explode.
$arr = explode('_', $fileinfo['basename']);
echo $arr[0];
This will split the string into an array of substrings. The length of the array depends on how many instances of _ there was. For example
"one_two_three"
Would be broken into an array
["one", "two", "three"]
Here's some documentation
If you want an old-school answer in the type of what you proposed you can still do the following:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
I have the following URI:
/belt/belts/fk/product/40P35871
And I want to retrieve the last content after the last /.
In this case is 40P35871.
How can I do this?
How about explode?
$elements = explode('/', $input);
$productId = end($elements);
Here's a different solution entirely. (and the simplest!)
Using basename
$var = "/belt/belts/fk/product/40P35871";
echo basename($var);
Output:
40P35871
You don't need regex for something simple like that. Consider using strrchr, documentation here
$lastcontent = substr(strrchr($uri, "/"), 1);
Considering this special case of $uri being a path, the best answer would be the one provided by Chtulhu.
basename will return the last part of a path, documentation here
$lastcontent = basename($uri);
Just like this
$str = '/belt/belts/fk/product/40P35871';
$arr = explode('/', $str);
$var = array_pop($arr);
var_dump($var);
or
$var = substr($str, strrpos($str,'/') + 1);
Try this
$result = preg_replace('%(/(?:[^/]+?/)+)([^/]+)\b%', '$2', $subject);
use this:
echo preg_replace('/[a-z0-9]$/i', '$1', $url);
this will give you the last position
note: but on this url only, query strings make this useless and use need to parse the url for the same first for this to work
Don't use regex. In this case you can act as the follow
myUrl = $_SERVER[REQUEST_URL];
$number = substr(strrpos(myUri,'/')+1);
You don't need regex.
Find the last content and get it using substr():
$lastcontent = substr(strrchr($uri, "/"), 1);