Is it possible in PHP to retrieve part of a string using the same notation as Python?

1

I have the following variable for example:

$teste = 'Uma frase qualquer!';

In Python , for me to retrieve the word frase , I would use the notation variavel[inicio:fim] :

teste = 'Uma frase qualquer!'
print(teste[4:9]) # frase

Is it possible to use the same notation in PHP ?

    
asked by anonymous 31.03.2018 / 04:11

2 answers

1

No, not least because PHP does not treat strings as just another collection of data (characters) in sequence, as Python does.

The only way is to use a function such as substr() . Unless you want to write a compiler that reads a new form and manages pure PHP code.

But there's a catch there. In Python you use the start and end position of what you want to pick up. The PHP function indicates the starting position and how many positions to take in the total. Then it would look like this:

print substr($teste, 4, 5);
    
31.03.2018 / 04:19
1

In php you do this:

$texto= 'Uma frase qualquer!';
                    //O primeiro parâmetro é de onde começa, o outro é onde termina
echo substr($texto, 0, 10);

You can also do:

echo substr($texto, -10);
//Isso pegará os caracteres a partir do último para esquerda

echo echo substr($texto, 11);  //Mostrará todos após o index 11

echo substr($texto, 11, 9)  //Isso mostrará do index 11 até 9 letras após ele, ex:    
$texto = "eu não sou besta pra tirar onda de herói";
echo substr($texto, 11, 9);  // besta pra

Source: link

    
31.03.2018 / 04:19