Using strpos in a variable with PHP

3

The following example tells me if the text of the variable $ phrase contains a S as a letter.

$frase="respuesta en ingles";
$posicion_coincidencia = strpos($frase, s);
if ($posicion_coincidencia === false) 
{
echo "La $frase";
} else {
echo "Las $frase";
}

My question: What I need from the text of the $ phrase variable is:

If it does not contain the letter (S) at the end of the first word, show me (The $ phrase) and if it contains the letter > (S) at the end of the first word show me on screen (Las $ frase) .

That is, show me (LA or LAS) depending on whether there is (s) or (no) in the first word of the indicated phrase.

I hope you understand me. Thank you very much.

    
asked by juan pablo 11.12.2018 в 22:18
source

3 answers

3

You need to separate the phrase and check the last character of the first word. You can do it using explode and strlen like this:

<?php

$frase="respuesta en ingles";
$palabras = explode(' ', $frase);
$ultima = strlen($palabras[0]);
$posicion_coincidencia = $palabras[0][$ultima - 1];
if ($posicion_coincidencia !== "s") 
{
echo "La $frase";
} else {
echo "Las $frase";
}
?>
    
answered by 11.12.2018 / 22:24
source
2

I can think of two possible ways:

Alternative # 1: regular expression.

The following regular expression will take as valid if there is a word that at the beginning of a given sentence and that at the end contains the letter "s".

^\w+s(?=\b)

It can be used in the following way:

if (preg_match('/^\w+s(?=\b)/i', $frase)) {
    echo "Las $frase";
} else {
    echo "La $frase";
}

Alternative # 2: split the chain.

$palabras = explode(' ', $frase);
$primerPalabra = $palabras[0];

if (strrpos($primerPalabra, 's') === strlen($primerPalabra) - 1)) {
    echo "Las $frase";
} else {
    echo "La $frase";
}
    
answered by 11.12.2018 в 22:45
0

I would use the function substr with negative index to obtain the last character of the first word separated by spaces with the function explode , the code is cleaner and readable.

$frase="respuesta en ingles";
if ( substr(explode($frase,' ')[0], -1, 1) == 's'){
    echo "La $frase";
} else {
    echo "Las $frase";
}

link

    
answered by 11.12.2018 в 22:28