I have a variable in php called
$nombre = "img.jpg";
(The string could be: "www.example.com/content/something.jpg")
I want to find a way to add something in the middle of the string
$nombre = "img-150x150.jpg";
the solution i found
$imagenTMP = explode(".", $imagen);
$imagen = $imagenTMP[0].'.'.$imagenTMP[1].'.'.$imagenTMP[2]."-150x150.".$imagenTMP[3];
I can think of two ways
Splitting the name :
With
explode
, parts$nombre
in two by the . (and this one is deleted, so it has to be put back)Replacing :
This last example I think is better, since it will not give you problems if
$nombre
there is any '.'For security, I would take the file extension. SINCE that way you can be calm if a jpg , png , gif , whatever it is, comes to you.
So you can be sure that you will change in string that you pass the extension to the text that you want
You have the example here
Do you want something to always be added right in the middle of the string?
If so, you have to check the length of the string and break it in half, and concatenate whatever you want right in the middle, this is done as follows:
If you just want to add something before the
.
, you can do it with split:Hope this can help you.
It is possible to optimize the code, maybe someone who knows more about php can improve it, but this solution is still valid.
Cheer up!
Since you are going to use images, and your $file variable can be a url, I suggest that you use the functions provided by php in this regard.
A url could have something like this (may not be your case, but it could be):
The first thing is to take the path of this url. For this, php provides you with parse_url (see http://php.net/manual/es/function.parse-url.php ):
this returns "/content/content2/something.jpg", removing what's after the ? and eliminating the host, protocol and others.
Once you have the path, you should get the file. For that, there is already a function in php that solves it for you, it is basename ( http://php.net/manual/es/function.basename.php ):
This directly returns the name of the file, in your case "something.jpg"
And from here, apply explode as they have commented in other solutions.
You have a method called
explode()
from php that you can split the String from wherever you want and it stores them in an array.An example of its use is this:
The first thing that comes to mind, like this soon:
You could divide the String into two pieces (on the one hand the name of the file and on the other hand the extension of the file) using the "." as the delimiter character.
Then assign each of the "chunks" to a variable.
Concatenate what you want to the piece that interests you (in your case at the end of $file_name).
And all you have to do is join the pieces again, without forgetting to add the "." separator between the name of the file and its extension.
I hope I helped you ^^