Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get one letter on two from a string

Tags:

php

I have a string like :

12121212

I want to get only 1111, the first letter, then the third, then the fifth ... one letter on two.

Is there any function for this ? I am using str_split then I take the first letter of my array, but it's not very clean. Thanks.

This is my code for now, but it's not very flexible :

function loop_n_letter($string, $n)
{
    $return = '';
    $array = str_split($string);

    foreach ($array as $i => $row)
    {
       if ($i % $n == 0)
       {
           $return .= $row[0];
       }
    }

    return $return;
}
like image 874
Vincent Decaux Avatar asked May 27 '15 16:05

Vincent Decaux


People also ask

How to get the first 2 letters of a string in JavaScript?

That means the first 2 characters can be or cannot be letters, numbers, or special characters. There are numerous ways to get the first 2 letters of a string. A string consists of multiple characters and to extract only letters from it, we can make use of the regular expression. To further get the first 2 letters, we can use the slice () method.

How to extract two characters from a string in Excel?

1. Select a cell that used to place the extracted substring, click Kutools > Formula Helper > Text > Extract strings between specified text. 2. In the Formulas Helper dialog, go to the Arguments input section, then select or directly type the cell reference and the two characters you want to extract between.

How do I extract one letter from each word in Excel?

In cell B2, we've created the following formula to extract one letter from each of the words: This formula will use the MID function to extract 1 letter from each word and then concatenate the letters together using the & operator.

How do I get a single character from a string?

Another option to obtain a single character is to use the std::string::at () member function. To obtain a substring of a certain length, use the std::string::substr member function.


2 Answers

Recall that you can get a character of a string by simply calling the specific index of the string. Try using a for loop like so:

$string = '12121212';
$length = strlen($string);
$result = '';
for ($i = 0; $i < $length; $i = $i + 2) {
    $result .= $string[$i];
}
die($result);

You can change the index and the increment to get different parts of the string

like image 168
Anuj Avatar answered Oct 11 '22 05:10

Anuj


Here's one with regular expressions:

$str = '12121212';
echo preg_replace('<(.)(.)>', '$1', $str);
like image 23
Fabian Schmengler Avatar answered Oct 11 '22 04:10

Fabian Schmengler