Question:
If the nomenclature of substr is:
string substr ( string $string , int $start [, int $length ] )
How do I tell it that it has to take me the start string until it finds a "." of the extension?
That is: if we have "string.php", extract only "string".
Answer:
You can do this by combining substr
with strpos
, or by exploding with .
<?php
$cadena='archivo.php';
// opcion 1
$cadena_cortada = substr($cadena,0, strpos($cadena,'.'));
print_r('<br>opción 1 "'.$cadena_cortada.'"');
// opcion 2
$cadena_arr = explode('.',$cadena);
print_r('<br>opción 2 "'.$cadena_arr[0].'"');
Option 1 is closer to what you're trying to do, but if you pass it a character that isn't in the string, the result will be an empty string.
With the explode
option it will always return something to you.
Now, if you want it to return the string from the beginning to the last occurrence of a character, there you have to start checking, for example using strpos
to verify that the character exists, or exploiting and verifying the length of the resulting array. Say for example your string is archivo.con.datos.php
and you want just archivo.con.datos
$cadena_arr2 = explode('.','archivo.con.datos.php');
$elementos = count($cadena_arr2);
print_r('<br>La cadena explotada tiene '.$elementos.' elementos');
if($elementos>1) {
// quitamos el último elemento
array_pop($cadena_arr2);
}
print_r('<br>opción 3 "'.implode('.',$cadena_arr2).'"');