Remove PHP text string - substr

1

If the substring nomenclature is:

string substr ( string $string , int $start [, int $length ] )

How do I tell him he has to pick up the start string until he finds a "." of the extension?

That is: if we have "cadena.php", extract only "string".

    
asked by omaza1990 13.12.2017 в 12:21
source

2 answers

2

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).'"');
    
answered by 13.12.2017 / 12:26
source
1

substr() only allows you to start from the indicated position and continue the number of characters you indicate.

Use explode ()

$string = "cadena.php";
$resultado = explode(".", $string);

With substr() you can not tell the character you want to end, that's what explode() is for.

    
answered by 13.12.2017 в 12:24