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

Asked

Viewed 64 times

1

I have the following variable for example:

$teste = 'Uma frase qualquer!';

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

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

It is possible to use the same notation in PHP?

  • With the function replace you get similar effect, but not as elegant as python.

  • I don’t think so, the kind of data string is implemented differently in PHP and Python.

2 answers

1

In php you do so:

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

It is also possible to 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: http://codare.aurelio.net/2007/05/22/php-cortando-strings-substr/

1


No, even because PHP does not treat strings as only one more collection of data (characters) in sequence, as Python does.

The only way is to use a function like the substr(). Unless you want to write a compiler that reads a new way and generates pure PHP code.

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

print substr($teste, 4, 5);

I put in the Github for future reference.

  • That doubt arose after I saw in the documentation: $string = 'bar'; echo "The last character of '$string' is '$string[-1]'.\n"; which in this case returns the last character.

  • If you take only one character it works, but there’s no way to get a track.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.