You can do it by combining substr
with strpos
, or exploiting 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 are trying to do, but if you pass a character that is not in the string, the result will be an empty string.
With the option of explode
you will always return something.
Now, if you want to return the string from the beginning to the last occurrence of a character, there you have to start checking, for example by using strpos
to verify that the character exists, or by exploiting and verifying the length of the resulting array. Let's say for example that your string is archivo.con.datos.php
and you want only 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).'"');