I am new to php.
I am getting default image path as \xampp\htdocs\Sample\tmp/one.jpg
and i have to replace \xampp\htdocs with http:\localhost
If i use in this way i am getting required output
$absolute = "\xampp\htdocs";
$relative = "http:\\localhost";
$imagepathurl = "\xampp\htdocs\Sample\tmp\/safety-masks_5092610ad4f3f.jpg";
echo str_replace($absolute,$relative,$imagepathurl);
But i am getting the $imagepathurl from database. If i use this in same formate i am not getting result
$absolute = "\xampp\htdocs";
$relative = "http:\\localhost";
$imagepathurl = '"'.$imagepath.'"';
echo str_replace($absolute,$relative,$imagepathurl);
In the secound listing when you add " before and after the $imagepath why?
Remove this line $imagepathurl = '"'.$imagepath.'"'; and it should work:
$absolute = "\xampp\htdocs";
$relative = "http:\\localhost";
echo str_replace($absolute,$relative,$imagepath);
Update (Example what the line does)
$var = "MyString"; // Content of the String => MyString
$var = '"'.$var.'"'; // Content of the String => "MyString"
Use the function pathinfo to get an array as result with all the components of your path.
Then you can replace the part that you want to change and concatenate the path components again to get the desired new path.
The way commented in the other posts is just a string manipulation solution. If you want something safe when dealing with parsing paths you should use the php function pathinfo. If is some quite simple then the str_replace will do the work.
make sure that your database does not applies any character encoding on string if it applies any then first decode the sting value and then use this code.
$absolute = "C:\xampp\htdocs";
$relative = "http:\\localhost";
// if database contains encoded string decode first here
//creating absolute path for image (this will remove ./, ../ \, / to create operating system preferred path as windows uses \ and linuz user / as path separator )
$imagepathurl = realpath($imagepathurl);
// replasing absolute path to root directory with relative path
echo str_replace( $absolute , $relative , $imagepathurl);
Related
Having directory named "Łęć"
and using glob like this:
$dirs = glob( FILES . '/general/*' );
Gives me the result of:
...
(string) "../pliki/general/Logo"
(string) "../pliki/general/���"
(string) "../pliki/general/Maski"
...
And this ��� is the directory named Łęć
I totally can't figure it out how to make it work, so I can have folders with special characters and the glob() to work with it properly
$dirs = glob( FILES . '/general/q/*' );
foreach($dirs as &$dir)
{
$dir = bin2hex($dir);
}
dd($dirs);
This code above globs where Łęć folder is and bin2hex it's name returns: 2e2e2f706c696b692f67656e6572616c2f712fa3eae6 and the folder name alone without the path is a3eae6
a3eae6 is the hexadecimal representation of the string of unknown encoding returned for "Łęć". The string returned by glob() can write in PHP-Notation as "\xa3\xea\xe6". The conversion of this character string with an encoding unknown to us into UTF-8 must then result "Łęć".
Through trial and error, I found that the "ISO-8859-2" encoding satisfies this condition:
$strCode = "\xa3\xea\xe6";
$name = mb_convert_encoding($strCode,"UTF-8","ISO-8859-2");
var_dump($name === "Łęć"); //bool(true)
The strings that glob returns must all be converted with mb_convert_encoding:
$fullNameUTF8 = mb_convert_encoding($strFromGlob,"UTF-8","ISO-8859-2");
This procedure is not certain. It's better to know the exact encoding used by the file system you are accessing.
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
This question already has answers here:
How do I get a file name from a full path with PHP?
(14 answers)
Closed 8 years ago.
My input value is just like this: Oppa/upload/default.jpeg
I want to slice the value of an input according by / cause i want to get the image file name. Does anyone know some tricks to do this?
example: i want to get default.png
<input type="text" value="Oppa/upload/default.png" id="fileLink" name="fileLink" />
Use basename():
$path = "Oppa/upload/default.jpeg";
echo basename($path); //will output "default.jpeg"
echo basename($path, '.jpeg'); //will output "default"
The first parameter is the path of which the trailing component will be removed. If the first parameter ends in the optional second parameter, the second parameter will also be cut off.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
- PHP manual
You should use basename() PHP function.
This will work for you
$path = "Oppa/upload/default.jpeg";
echo basename($path);
Use pathinfo() php function
$path = "http://domain.tld/Oppa/upload/default.png";
$info = pathinfo ( $path, PATHINFO_BASENAME ); // returns default.png
Yet another solution, using preg_match()
<?php
$path = "http://domain.tld/Oppa/upload/default.png"; // or "C:\\domain.tld\Oppa\upload\default.jpg";
$pattern = '/[\/|\\\\]((?:.(?!\/|\\\\))+)$/';
if(preg_match($pattern, $path, $matches)){
echo $matches[1]; // default.png or default.jpg
}
?>
Note: People claim to have problems using basename() with asian characters
I am supposing that if your image path will not be change from Oppa/upload/ than this Should work using explode :
$str = "Oppa/upload/default.jpeg";
$s= explode("Oppa/upload/",$str);
echo $s[1];
Another Best thing you can do with defining the relative path as a constant, so :
const path = "Oppa/upload/";
$str = "Oppa/upload/default.jpeg";
$s= explode(path,$str);
echo $s[1];
will also work.
I have a string with a path like so:
C:/myfolder/mysubfolder/myfile.doc
I need to truncate the string to become:
myfile.doc
Needless to say, I have a list of such paths with different lengths and different folder depths. What I need is something like trancating the rest of the string beginning from the last of the string till the first / is encountered.
How can I achieve this in PHP.
Many thanks
$path = 'C:/myfolder/mysubfolder/myfile.doc':
$filename = basename($path);
echo $filename; // "myfile.doc"
See Manual "basename()". For more detailed information about a path see pathinfo()
You can use the basename() function for this.
echo basename("C:/myfolder/mysubfolder/myfile.doc");
Output:
myfile.doc
Note that this doesn't exactly do what you described, because for these inputs:
/etc/
.
it would return
etc
.
So an (untested) alternative could be:
$fullname = "C:/myfolder/mysubfolder/myfile.doc";
$parts = explode("/", $fullname);
$filename = $parts[count($parts)-1];
echo $filename;
If you mean you want the filename segment, you can use basename()
http://php.net/manual/en/function.basename.php
I have a following string and I want to extract image123.jpg.
..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length
image123 can be any length (newimage123456 etc) and with extension of jpg, jpeg, gif or png.
I assume I need to use preg_match, but I am not really sure and like to know how to code it or if there are any other ways or function I can use.
You can use:
if(preg_match('#".*?\/(.*?)"#',$str,$matches)) {
$filename = $matches[1];
}
Alternatively you can extract the entire path between the double quotes using preg_match and then extract the filename from the path using the function basename:
if(preg_match('#"(.*?)"#',$str,$matches)) {
$path = $matches[1]; // extract the entire path.
$filename = basename ($path); // extract file name from path.
}
What about something like this :
$str = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$m = array();
if (preg_match('#".*?/([^\.]+\.(jpg|jpeg|gif|png))"#', $str, $m)) {
var_dump($m[1]);
}
Which, here, will give you :
string(12) "image123.jpg"
I suppose the pattern could be a bit simpler -- you could not check the extension, for instance, and accept any kind of file ; but not sure it would suit your needs.
Basically, here, the pattern :
starts with a "
takes any number of characters until a / : .*?/
then takes any number of characters that are not a . : [^\.]+
then checks for a dot : \.
then comes the extension -- one of those you decided to allow : (jpg|jpeg|gif|png)
and, finally, the end of pattern, another "
And the whole portion of the pattern that corresponds to the filename is surrounded by (), so it's captured -- returned in $m
$string = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
$data = explode('"',$string);
$basename = basename($data[1]);