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.
Related
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
I need a regular expression that would take the string after the last forward slash.
For example, considering I have the following string:
C:/dir/file.txt
I need to take only the file.txt part (string).
Thank you :)
You don't need a regex.
$string = "C:/dir/file.txt";
$filetemp = explode("/",$string);
$file = end($filetemp);
Edited because I remember the latest PHP spitting errors out about chaining these types of functions.
If your strings are always paths you should consider the basename() function.
Example:
$string = 'C:/dir/file.txt';
$file = basename($string);
Otherwise, the other answers are great!
The strrpos() function finds the last occurrence of a string. You can use it to figure out where the file name starts.
$path = 'C:/dir/file.txt';
$pos = strrpos($path, '/');
$file = substr($path, $pos + 1);
echo $file;
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, '/'), '/');
I have a url, - "http://example.com/sales/view/id/705" and I need get a last segment (705).
How can I do this using PCRE?
This should do it in Perl:
my ($last) = $url =~ /([^\/]+)\z/;
But I would rather use the URI module:
my $last = (URI->new($url)->path_segments)[-1];
(In PHP) I would not use PCRE for such a trivial and un-ambiguous job. I would just do:
$parts = explode('/', rtrim($url, '/'));
$partYouWant = array_pop($parts);
EDIT
If you need to use PCRE (although I don't know why you would) this variation on eugene y's answer would do it:
$pattern = '#/([^/]+)\z#';
$url = 'http://example.com/sales/view/id/705';
preg_match($pattern, $url, $matches);
echo $matches[1];
In PHP you can do this in a single line code:
$url = 'http://example.com/sales/view/id/705';
substr($url, strrpos($url, '/') + 1);
Non PCRE alternative:
$url="http://example.com/sales/view/id/705";
$lastPart = current(array_reverse((explode('/',parse_url($url,PHP_URL_PATH)))));
Doubt if it's any faster though
You could use this pattern ([^\/]*)$ for everything from last / to end.
Maybe also interesting: ([^\/\?]*)(\?.*)?$ gives you everything between last / and first ?
Say no to PCRE if you can,:-).
echo basename('http://example.com/sales/view/id/705');
preg_match('#/([1-9]\d*)/?(?:$|\?)#', $url, $matches);//$matches[1] contains your id
Simplest:
$ok=preg_match('#\d+$#',$url,$m);
if($ok)
echo $m[0],"\n";
Brainy:
$ok=preg_match('#/(\d+)$#',$url,$m);
if($ok)
echo $m[1],"\n";
Flexible: (as it also allows words, other than digits)
$ok=preg_match('#/(\w+)$#',$url,$m);
if($ok)
echo $m[1],"\n";
More flexible: (as it now allows everything that's not a / to match)
$ok=preg_match('#/(.*?)$#',$url,$m);
if($ok)
echo $m[1],"\n";
I am trying to sanitize a filename.
I would like to know of a way to remove all decimals from a files name except the last one. I need to keep the last one because the extension follows that.
EXAMPLE:
abc.def.ghij-klmnop.q234.mp3
This file should look like
abcdefghij-klmnopq234.mp3
Some extensions are longer than 3 characters.
You can use a regex with a positive lookahead. Like this:
$withdots = 'abc.def.ghij-klmnop.q234.mp3';
$nodots = preg_replace('/\.(?=.*\.)/', '', $withdots);
After executing the above, $nodots will contain abcdefghij-klmnopq234.mp3. The regular expression is basically saying match all periods that are followed by another period. So the last period won't match. We replace all matches with an empty string, and we're left with the desired result.
That should do it:
$file = 'abc.def.ghij-klmnop.q234.mp3';
$parts = pathinfo($file);
$filename = str_replace('.', '', $parts['filename']).'.'.$parts['extension'];
You could also do this, it should be faster then using pathinfo & str_replace.
$parts = explode('.', 'abc.def.ghij-klmnop.q234.mp3');
$ext = array_pop($parts);
$nodots = implode('', $parts) . '.' . $ext;
Assuming $s is the name of the file.
$s = (($i = strrpos($s, '.')) === false) ? $s :
str_replace('.','',substr($s,0,$i)).substr($s,$i);