I want to remove ".php" from the end of a string if it exists. Consider this:
$filename = 'index';
rtrim($filename,".php");//returns "index"
$filename = 'search';
rtrim($filename,".php");//returns "searc"
Why is this happening? I feel like it has something to do with ending with the letter 'h' - 'h' being in the string in rtrim. So I tried a regular expression (.php$) to see if it made a difference but it didn't.
rtrim accepts a list of characters as the second argument, so in this case, it will trim not just the .php extension, but any ., p, or h characters found in the rest of the string.
Try using preg_replace("/(.+)\.php$/", "$1", $filename); instead, or basename($filename, '.php') if you have the file on the server, not just in a string.
The second argument to rtrim is a string with a list of characters. In this case, it will strip off any P, H, and . in your string, so returning searc.
if you're simply trying to remove the extension, why not use this:
$filename = 'index.php';
$name = strstr($filename, '.', true);
Related
Given the following URL:
http://www.domain.com/reporting/category-breakdown.php?re=updated
I need to remove everything after the .php
It might be "?re=updated" or it could be something else. The number of characters won't always be the same, the string will always end with .php though.
How do I do this?
To find the first position of a substring in a string you can use strpos() in PHP.
$mystring = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$findme = '.php';
$pos = strpos($mystring, $findme);
After, you have the position of the first character of your substring '.php' in your URL. You want to get the URL until the end of '.php', that means the position you get + 4 (substring length). To get this, you can use substr(string,start,length) function.
substr($mystring, 0, $pos + 4);
Here you are!
Find the first indexOf (".php"), then use substring from char 0 to your index + the length of (".php");
3 line solution:
$str = "http://www.domain.com/reporting/category-breakdown.php?re=updated";
$str = array_shift(explode('?', $str));
echo $str;
Note: it's not fool-proof and could fail in several cases, but for the kind of URLs you mentioned, this works.
Here is another way to get the non-query-string part of a url with PHP:
$url = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$parsed = parse_url($url);
$no_query_string = $parsed['scheme'] . '://' . $parsed['hostname'] . $parsed['path'];
// scheme: http, hostname: www.domain.com, path: /reporting/category-breakdown.php
That will handle .php, .phtml, .htm, .html, .aspx, etc etc.
Link to Manual page.
Lets say I have $url="../folder/file" and I want to find and remove the ../ part.
I'm using trim() …
$url = trim($url,"../");
… but it gives me a warning:
Warning: trim() [function.trim]: Invalid '..'-range, no character to the left of '..' on line above
What I did wrong?
what you did wrong was fail to read the manual:
With .. you can specify a range of characters.
<?php
$url="../folder/file";
$url = trim($url,"\.\./");
echo $url;
?>
you can use ltrim
echo ltrim("../folder/file", "./");
or
echo trim("../folder/file", "./");
There is a special syntax in the trim function from php.net/trim that allows you to specify a range, which is what the interpreter believes you are doing because of the '..'
// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
The second argument to trim should be a string of characters that would be stripped, so you should not have to put the '.' twice.
The second argument to the trim function specifies a list of characters to be stripped, not a multi-character string. The function interprets '..' as an operator specifying a range of characters (like a..z or 1..5). You can strip out the '../' in a number of ways, but one easy one is this:
$parts = explode('/', $url);
array_shift($parts);
$url = implode('/', $parts);
I found this function in bottom comments of the trim page on php.net that seem to do what you want
function trimString($input, $string){
$input = trim($input);
$startPattern = "/^($string)+/i";
$endPattern = "/($string)+$/i";
return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
}
I have a script to upload files with PHP.
I already do some cleaning to remove ugly characters.
I would also like to to remove dots in the filename, EXCEPT for the last one, which indicates the file extension.
Anyone has an idea how I could do that.?
For example, how would you get
$filename = "water.fall_blue.sky.jpg";
$filename2 = "water.fall_blue.sky.jpeg";
to return this in both cases..?
water.fall_blue.sky
Use pathinfo() to extract the file name (the "filename" array element is available since PHP 5.2); str_replace() all the dots out of it; and re-glue the file extension.
Here's an example of how this can be done:
<?php
$string = "really.long.file.name.txt";
$lastDot = strrpos($string, ".");
$string = str_replace(".", "", substr($string, 0, $lastDot)) . substr($string, $lastDot);
?>
It converts filenames like so:
really.long.file.name.txt -> reallylongfilename.txt
Check here: example
[Edit] Updated script, dot position is cached now
FILENAME = this/is(your,file.name.JPG
$basename=basename($_FILES['Filedata']['name']);
$filename=pathinfo($basename,PATHINFO_FILENAME);
$ext=pathinfo($basename,PATHINFO_EXTENSION);
//replace all these characters with an hyphen
$repar=array(".",","," ",";","'","\\","\"","/","(",")","?");
$repairedfilename=str_replace($repar,"-",$filename);
$cleanfilename=$repairedfilename.".".strtolower($ext);
RESULT = this-is-your-file-name.jpg
I have two example filename strings:
jquery.ui.min.js
jquery.ui.min.css
What regex can I use to only match the LAST dot? I don't need anything else, just the final dot.
A little more on what I'm doing. I'm using PHP's preg_split() function to split the filename into an array. The function deletes any matches and gives you an array with the elements between splits. I'm trying to get it to split jquery.ui.min.js into an array that looks like this:
array[0] = jquery.ui.min
array[1] = js
If you're looking to extract the last part of the string, you'd need:
\.([^.]*)$
if you don't want the . or
(\.[^.]*)$
if you do.
I think you'll have a hard time using preg_split, preg_match should be the better choice.
preg_match('/(.*)\.([^.]*)$/', $filename, $matches);
Alternatively, have a look at pathinfo.
Or, do it very simply in two lines:
$filename = substr($file, 0, strrpos($file, '.'));
$extension = substr($file, strrpos($file, '.') + 1);
At face value there is no reason to use regex for this. Here are 2 different methods that use functions optimized for static string parsing:
Option 1:
$ext = "jquery.ui.min.css";
$ext = array_pop(explode('.',$ext));
echo $ext;
Option 2:
$ext = "jquery.ui.min.css";
$ext = pathinfo($ext);
echo $ext['extension'];
\.[^.]*$
Here's what I needed to exclude the last dot when matching for just the last "part":
[^\.]([^.]*)$
Using a positive lookahead, I managed this answer:
\.(?=\w+$)
This answer matches specifically the last dot in the string.
I used this - give it a try:
m/\.([^.\\]+)$/
Let's say I have a string like so:
$file = 'widget-widget-newsletter.php';
I want to use preg_replace() to remove the prefix widget- and to remove the suffix .php . Is it possible to use one regular expression to achieve all this?
The resulting string should be widget-newsletter.
$file = preg_replace('/^widget-|\.php$/', '', $file);
Why not use substr? Much simpler and faster.
Don't think of it as stripping off the ends, rather as extracting the middle:
$file = 'widget-widget-newsletter.php';
if (preg_match('/^widget\-(.+)\.php$/i', $file, $matches))
echo "filename is " . $matches[1][0];
Of course, if "widget-" and ".php" are entirely static and are always going to be there, you could just use substr:
echo "filename is " . substr($file, 7, -4);
That would be much faster but if you pass it garbage, you'll get garbage back.
$name = preg_replace(array('%^widget-%', '%-%', '%\.php$%'), array('','_',''), $file);
should do it.
Or more general (assuming the prefix goes to the first - and the suffix starts at the last .):
$name = preg_replacearray('%^.*?-%', '%-%', '%\.(?!.*?\.).*?$%'), array('','_',''), $file);
If you provide an array of patterns and an array of replacements to the function, then each pattern gets replaced by the according replacement.
Update:
As you removed the requirement to replace the - by _, substr() is indeed better suited:
$name = substr($file, 7, -4);
From the manual description of the replacement parameter:
The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string.
Sounds like you could use an array with the prefix and suffix patterns in it for the pattern parameter, and just put empty string as the replacement.