eg:the GET array: $_GET['path']
which value may be : $_GET['path']==3,$_GET['path']==13_7,$_GET['path']==33_75_45,...
no matter what value $_GET['path'] has, i only want the first part of the value. how to get it?
list($a) =explode('_', $_GET['path']);
var_dump($a);
You could use something like this:
function getNumber($n)
{
$pos = strpos($n, "_");
return ($pos === false ? $n : substr($n, 0, $pos));
}
This will get the job done:
$splitPath = strstr($_GET['path'], "_", true);
$path = strlen($splitPath > 0) ? $splitPath : $_GET['path'];
It can probably be shortened a bit, but the idea here is that in the end you will always just use the $path variable. If $_GET['path'] contains _ then whatever number is before it will be returned (due to the true argument in strstr()) and if not then just the value of $_GET['path'] will be equal to $path. You may want to do some cleansing of the value though too, or at least make sure it's numeric (is_numeric()).
do you mean that the value of $_GET['path'] is delimited by _ ? if so,
<?php
list($firstPart,) = explode('_', $_GET['path'], 2);
echo $firstPart;
could be the one you need.
First of all your question is confusing
This may help you
if u want to find the first part
example : name3example.com
<?php
$result = strstr($_GET['path'], '3');
?>
// will return "name"
see the link for more details http://php.net/manual/en/function.strstr.php
Or if u want to get the part of a string u can use 'substr' function of php
see the link for more details http://www.php.net/manual/en/function.substr.php
Use parse_url in PHP to split an url in its various parts.
After that use strrpos to find the first occurrance of the required part in the path.
With substr you can copy the first part of the path (up until the found _) and you're done.
Related
I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon
I've got a problem. This is my PHP code :
$extract = $query;
$extractpoint = strrchr($extract, ".");
So, $extract is a parse_url of my website address.
Exemple : http://test.com?param.6
$extract = param.6 and $extractpoint = .6
BUT, I want a solution to have only the 6, without the point.
Can you help me with that ?
The easiest solution would be restructuring the URL. I that is not possible though you can use strpos to find the position of your specific character and then use substr to select the characters after it.
$extract = 'param.6';
echo substr($extract, strpos($extract, '.') + 1);
Demo: https://3v4l.org/CudTAG
(The +1 is because it returns the position of the match and you want to be one place past that)
There are different ways:
Filter only numbers:
$int = filter_var($extractpoint, FILTER_SANITIZE_NUMBER_INT);
Replace the point
$int = str_replace('.', '', $extractpoint)
//$int = str_replace('param.', '', $extractpoint)
Use regex
/[0-9+]/'
strrchr() results the count of the last instance of a character in a string. In order to get the next character add 1 to the count. Then use substr() to extract the next character from the string.
http://php.net/manual/en/function.strrchr.php
http://php.net/manual/en/function.substr.php
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);
My url like this:
http://mywebsite.com/movies/937-lan-kwai-fong-2?file=Rae-Ingram&q=
http://mywebsite.com/movies/937-big-daddy?file=something&q=
I want to get "lan-kwai-fong-2" and "big-daddy", so I use this code but it doesn't work. Please help me fix it ! If you can shorten it, it is so great !
$url= $_SERVER['REQUEST_URI'];
preg_replace('/\?file.*/','',$url);
preg_match('/[a-z][\w\-]+$/',$url,$matches);
$matches= str_replace("-"," ",$matches[0]);
First there are issue with your code which im going to go over because they are general things:
preg_replace does not work by reference so you are never actually modifying the url. You need to assign the result of the replace to a variable:
// this would ovewrite the current value of url with the replaced value
$url = preg_replace('/\?file.*/','',$url);
It is possible that preg_match will not find anything so you need to test the result
// it should also be noted that sometimes you may need a more exact test here
// because it can return false (if theres an error) or 0 (if there is no match)
if (preg_match('/[a-z][\w\-]+$/',$url,$matches)) {
// do stuff
}
Now with that out of the way you are making this more difficult than it needs to be. There are specific function for working with urls parse_url and parse_str.
You can use these to easily work with the information:
$urlInfo = parse_url($_SERVER['REQUEST_URI']);
$movie = basename($urlInfo['path']); // yields 937-the-movie-title
Just replace
preg_replace('/\?file.*/','',$url);
with
$url= preg_replace('/\?file.*/','',$url);
Regex works, and parse_url is the right way to do it. But for something quick and dirty I would usually use explode. I think it's clearer.
#list($path, $query) = explode("?", $url, 2); // separate path from query
$match = array_pop(explode("/", $path)); // get last part of path
How about this:
$url = $_SERVER['REQUEST_URI'];
preg_match('/\/[^-]+-([^?]+)\?/', $url, $matches);
$str = isset($matches[1]) ? $matches[1] : false;`
match last '/'
match anything besides '-' until '-'
capture anything besides '?' until (not including) '?'
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];