How to get the position of the last letter in a string in php?

Example line: "Some text.....!!!!!!!!?????"

Using PHP, how would I get the position of the last letter (or even the alphanum character), which in this example is a letter t?

+3
source share
7 answers

You can use preg_match_allwith regex \p{L}to find all Unicode letters . With the optional PREG_OFFSET_CAPTURE flag, you also get offsets:

$str = "Some text.....!!!!!!!!?????";
if (preg_match_all('/\p{L}/u', $str, $matches, PREG_OFFSET_CAPTURE) > 0) {
    $lastMatch = $matches[0][count($matches[0])-1];
    echo 'last letter: '.$lastMatch[0].' at '.$lastMatch[1];
} else {
    echo 'no letters found';
}
+4
source
$s = "Some text.....!!!!!!!!embedded?????";

$words = str_word_count($s,2);
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1;
echo $lastLetterPos;

If you want to allow the alphabetic alphabet, not just alpha:

$s = "Some text.....!!!!!!!!embedded21?????";

$words = str_word_count($s,2,'0123456789');
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1;
echo $lastLetterPos;

To add other characters as valid:

$s = "Some text.....!!!!!!!!embedded!!à?????"; 

$words = str_word_count($s,2,'0123456789ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ'); 
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1; 
echo $lastLetterPos; 
+2
source

substr();)

echo substr ('abcdef', -1, 1);

+1

, , , "Some!!!???text???!!!", :

, , , , . ( , , , .)

, , . ( , , , .)

0

:

<?php
    $s = "Some text.....!!!!!!!!?????";
    $ary = str_split($s);
    $position = 0;
    $last = 0;
    foreach ($ary as $char) {
        if (preg_match("/[a-zA-Z0-9]/", $char)) {
            $last = $position;
        }
        $position += 1;
    }
    echo $last;
?>
0
<?php

$str    = '"Some text.....!!!!!!!!?????"';
$last   = -1;

foreach(range('a', 'z') as $letter)
{
    $last = max($last, strripos($str, $letter));
}

echo "$last\n"; // 9

?>
0

O (n).

ctype_alpha():

C [A-Za-z]

If you need a different locale, you should abstract the function, which determines whether the character is alpha or not. This way you can save this algorithm and adapt to different languages.

function lastAlphaPosition($string) {
    $lastIndex = strlen($string)-1;
    for ($i = $lastIndex; $i > 0; --$i) {
        if (ctype_alpha($string[$i])) {
            return $i;
        }
    }
    return -1;
}

$testString = 'Some text.....!!!!!!!!?????';
$lastAlphaPos = lastAlphaPosition($testString);

if ($lastAlphaPos !== -1) {
    echo $testString[$lastAlphaPos];
} else {
    echo 'No alpha characters found.';
}
0
source

Source: https://habr.com/ru/post/1747309/


All Articles