I have a string like this being entered into my database that I can't format before it gets stored :
image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg#32e2e9a111a4f9f4aa01dbad2ca2aa403c994d28
The only part of that string that I want to use is this :
hglz466d8mm1pazysaoh.jpg
I'm trying to use strpos to remove the excess data.
So far I've managed to remove everything after and including the hashtag
($data is the original string) :
$dataclean = substr($data, 0, strpos($data, "#"));
This works as expected with $dataclean returning :
image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg
But I don't know how to remove the rest of the excess data :
image/upload/v1440427262/
Also, can this all be done in one hit or does it have to be split into several operations?
Use basename:
$dataclean = basename(substr($data, 0, strpos($data, "#")));
If basename() doesn't work I would explode the string by the forward slash.
$data = 'image/upload/v1440427262/hglz466d8mm1pazysaoh.jpg#32e2e9a111a4f9f4aa01dbad2ca2aa403c994d28';
$pieces = explode("/", $data);
$dataclean = substr($pieces[3], 0, strpos($data, "#"));
As mentioned in the question, first remove values after # using
$link = substr($data, 0, strpos($data, "#"));
Then use basename() function to access filename from the URL.
For example,
$link = "http://example.com/folderPath/filename.php";
echo basename($link); // It will return filename.php
Nothing wrong with substr + strpos, but it looks like your string is a URL, so you could use parse_url to isolate the path before using basename. Just another option FYI.
basename(parse_url($yourString, PHP_URL_PATH));
You can use a regex function:
preg_match("/[a-z0-9]+\.[a-z]{3}/i", $input_line, $output_array);
Try the code
Related
http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);
The problem is that urlencode will also encode the slashes which makes the URL unusable. How can i encode just the last filename ?
Try this:
$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));
You're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.
First of all, here's why you should be using rawurlencode instead of urlencode.
To answer your question, instead of searching for a needle in a haystack and risking not encoding other possible special characters in your URL, just encode the whole thing and then fix the slashes (and colon).
<?php
$myurl = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$myurl = rawurlencode($myurl);
$myurl = str_replace('%3A',':',str_replace('%2F','/',$myurl));
Results in this:
http://www.example.com/some_folder/some%20file%20%5Bthat%5D%20needs%20%22to%22%20be%20%28encoded%29.zip
Pull the filename off and escape it.
$temp = explode('/', $myurl);
$filename = array_pop($temp);
$newFileName = urlencode($filename);
$myNewUrl = implode('/', array_push($newFileName));
Similar to #Jeff Puckett's answer but as a function with arrays as replacements:
function urlencode_url($url) {
return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}
I am not much used to using rtrim and Reg expressions. So I wanted to get my doubt cleared about this:
Here is a url: http://imgur.com/r/pics/paoWS
I am trying to use rtrim function on this url to pick out only the 'paoWs' from the whole url.
Here is what i tried:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$yid=rtrim( $video_id, '/' );
And i am using '$yid' to hotlink the image from imgur. But What I get after trying this function is:
$yid= '/r/pics/paoWS'
How do I solve this?
rtrim is used for trimming down a string of certain characters or whitespace on the right-hand side. It certainly shouldn't be used for your purpose.
Assuming the URL structure will always be the same, you could just do something like this:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$parts = explode('/', $video_id)
$yid = end($parts);
You sould not use regular expressions (whitch are 'expensive') for a so 'simple' problem.
If you want to catch the last part of the URL, after the last slash, you can do :
$urlParts = explode('/', 'http://imgur.com/r/pics/paoWS');
$lastPart = end($urlParts);
rtim( strrchr('http://imgur.com/r/pics/paoWS' , '/') ); rtrim + strrchr
substr(strrchr('http://imgur.com/r/pics/paoWS', "/"), 1); substr + strrchr
rtrim() returns the filtered value, not the stripped characters. And your usage of it isn't proper too - it strips the passed characters from the right side. And you don't need parse_url() either.
Proper answers have been given already, but here's a faster alternative:
$yid = substr($yurl, strrpos($yurl, '/')+1);
Edit: And another one:
$yid = ltrim(strrchr($yurl, '/'), '/');
So I see split is no good anymore or should be avoided.
Is there a way to remove the LAST Ampersand and the rest of the link.
Link Before:
http://www.websitehere.com/subdir?var=somevariable&someotherstuff&textiwanttoremove
Link After:
http://www.websitehere.com/subdir?var=somevariable&someotherstuff
Right now I am using this script:
<?php
$name = http_build_query($_GET);
// which you would then may want to strip away the first 'name='
$name = substr($name, strlen('name='));
//change link to a nice URL
$url = rawurldecode($name);
?>
<?php echo "$url"; ?>
It takes the whole URL (all Ampersands included)...the issue is, the site the link is coming from adds a return value &RETURNVALUEHERE, I need to remove the last "&" and the rest of the text after it.
Thanks!
Robb
using substr and strrpos
$url = substr($url, 0, strrpos($url, '&'));
you can use strrpos() like
$url = substr($orig_url, 0, strrpos($orig_url, "&"));
Without knowing the Real URL, I was able to come up with this:
<?php
// The string:
$string = "http://www.websitehere.com/subdir?var=somevariable&someotherstuff&textiwanttoremove";
// get the position of the last "&"
$lastPos = strrpos($string, "&");
// echo out the final string:
echo substr($string, 0, $lastPos);
If your input is already $_GET, removing the last value pair could simply be this:
http_build_query(array_slice($_GET, 0, -1));
i want to give regex a pattern and force it to read it all ..
http://example.com/w/2/1/x/some-12345_x.png
i want to target "some-12345_x"
i used this /\/(.*).png/, it doesnt work for some reason
how do i force it to remember it must start with / and end with .png?
If you always want to get the final file-name, minus the extension, you could use PHP's substr() instead of trying to come up with a regex:
$lastSlash = strrpos($url, '/') + 1;
$name = substr($url, $lastSlash, strrpos($url, '.') - $lastSlash);
Also, a more readable method would be to use PHP's basename():
$filename = basename($url);
$name = substr($filename, 0, strpos($filename, '.'));
To actually use a regex, you could use the following pattern:
.*/([^.]+).png$
To use this with PHP's preg_match():
preg_match('|.*/([^.]+).png$|', $url, $matches);
$name = $matches[1];
You can do:
^.*/(.*)\.png$
which captures what occurres after the last / till .png at the end.
You might need to use reg-ex in this situation for a particular reason, but here's an alternative where you don't:
$url = "http://example.com/w/2/1/x/some-12345_x.png";
$value = pathinfo($url);
echo $value['filename'];
output:
some-12345_x
pathinfo() from the manual
How about:
~([^/]+)\.png$~
this will match anything but / until .png at the end of the string.
$link = http://site.com/view/page.php?id=50&reviews=show
How can we add &extra=video after id=50?
id is always numeric.
url can have many other variables after ?id=50
&extra=video should be added before the first & and after the 50 (value of id)
It will be used this way:
echo 'Get video';
Thanks.
As Treffynnon says, the order seldomly matters. However, if you really need if for some reason, just use
parse_url to get the querystring
parse_str to create an array of parameter
array_splice to inject a parameter
http_build_query to rebuild a proper query string
This will do it for you
<?php
$linkArray = explode('&',$link);
$linkArray[0] += '&extra=video';
$link = implode('&',$linkArray);
?>
Explode will split the link string at every &, so it doesn't care how many elements you have in the url.
The first element, will be everything including the id=## before the first & sign. So we append whatever you want to appear after it.
We put our array together again as a string, separating each element by an &.
Is ID always the first post parameter? If so, then you could jsut do some sort of string manipulation. Use strpos($link, "&") to find out the position where you want to insert. Then do a few substr() based on that position and then append them all together. Its kind of hacky I know, but it will definitely work.
$pos = strpos($link, "&");
$first = substr($link, 0, $pos);
$last = substr($link, $pos);
$extra = "&extra=video";
$newLink = $first . $extra . $last;
See this link for some of the string manipulation functions that I mentioned above: http://us3.php.net/strings
i would suggest to use functions specifically aimed at url parsing, not general string functions:
$link = 'http://site.com/view/?id=50&reviews=show';
$query = array();
parse_str(parse_url($link, PHP_URL_QUERY), $query);
$query['extra'] = 'video';
$linkNew = http_build_url($link, array('query' => http_build_query($query)));