Get one letter for two from a string

I have a line like:

12121212

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

Is there any function for this? I use str_split, then take the first letter of my array, but this is not very clean. Thanks.

This is my code at the moment, but it is 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; } 
+5
source share
7 answers

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

 $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 increment to get different parts of the string

+6
source

Here is one with regular expressions:

 $str = '12121212'; echo preg_replace('<(.)(.)>', '$1', $str); 
+3
source

For PHP> = 5.5.0

 $result = implode( '', array_column( str_split($myString, $n), $n - 1 ) ); 
+2
source

In this specialized case, you can use implode () and explode ():

 $string=implode(explode('2', '121212')); echo $string; 

Otherwise, you can use a loop:

 $start='121212'; $string = ''; for ($i = 1; $i <= strlen($start); $i++) { if($i &1){ $string .= substr($start,$i,1); } } echo $string; 
0
source

Here is my attempt to rewrite your function:

 function loop_n_letter($string) { $output = ''; if (! is_string($string)) $string = (string) $string; for ($i = 0; $i < strlen($string); $i += 2) { $output .= $string[$i]; } return $output; } loop_n_letter('12121212'); 

As someone else noted, you can use the array style syntax to call characters at a specific position, so in the example about $string[1] will be 2 .

0
source

If you want to avoid converting a string to an array (and then back to a string):

 $string = '12121212'; $stringLength = strlen($string); $resultString = ''; for ($i=0; $i<$stringLength; $i+=2) { $resultString .= substr($string, $i, 1); } 
0
source

Regex Solution: /(\d)(?:\d)/ - capture the first digit, but not the next digit ?: = Do not capture

 preg_match_all('/(\d)(?:\d)/', '12121212', $matches); var_dump($matches[1]); 

Outputs

 array (size=4) 0 => string '1' (length=1) 1 => string '1' (length=1) 2 => string '1' (length=1) 3 => string '1' (length=1) 

or string

 $result = preg_replace('/(\d)(?:\d)/', "$1", '12121212'); 

Outputs

 string '1111' (length=4) 
0
source

All Articles