• 11
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

$str = "helloworld";

I want to create string

$newStr = "h l o o l ";

So as you can see i want to replace the chars in positions , 2,4,6,8,10 (assuming first character is in position 1).

I can do something like this

<?php

$str = 'helloworld';
$newStr = '';
for($i=0;$i<strlen($str);$i++) {
    if($i%2==0) {
        $newStr .=  $str[$i];
    } else {
           $newStr .= ' ';
    }
}

echo $newStr;

?>

But is there a more easier way or a one line in built function available to do this task .

Thanks in advance .

It is easily done with a regular expression:

echo preg_replace('/(.)./', '$1 ', $str);

The dot matches a character. Every second character is replaced with a space.

  • 10
Reply Report

Firstly you can increase your counter by two, so you don't have to check if it's odd. Secondly because strings are treated like char arrays you can access a char at position $i with $str[$i].

$str = "Hello World";
$newStr = $str;
for($i = 1; $i < strlen($str); $i += 2) {
  $newStr[$i] = ' ';
}
echo $newStr;

Have a Nice day.

[Edit] Thanks ringo for the hint.

  • 3
Reply Report

Try this, a little shorter then yours but is a one-liner as you asked.

$str    = 'helloworld';
$newStr = '';
for( $i = 0; $i < strlen( $str ); $i++) { $newStr .= ( ( $i % 2 ) == 0 ? $str[ $i ] : ' ' ); }
echo $newStr;
  • 2
Reply Report

I think a regex technique will be cleanest, but I'll show a couple more for contrast.

  1. preg_replace() allows the most concise, single-function call solution. The pattern employs the \K metacharacter to eliminate the need for a capture group (capture groups cost extra "steps", so avoid them when sensible). \K means forget any previously matched characters and restart the "fullstring match" from this point in the string. In other words, it consumes the odd characters (by the OP's definition of "odd|even") then discards them, then matches whatever single-byte chatacter comes next.

  2. Most laborious of my set of techniques, the multi-functional approach splits the input string into an array of strings with at most 2-characters, then if the substring has a second character, it is replaced with a space before being reattached to reconstructed string.

  3. A for loop is likely to be the best performing, but isn't the type of scripting that is instantly readable (that said, some people find regex hard to read). Note, it is important to not call strlen() on each iteration. To avoid this, cache the length before the loop or in the first parameter of the loop.

Code: (Demo)

$str = "helloworld";

echo preg_replace('~.\K.~', ' ', $str);

echo "\n---\n";

echo array_reduce(str_split($str, 2), function($carry, $item) {
         return $carry . $item[0] . (isset($item[1]) ? ' ' : '');
     });

echo "\n---\n";

for ($offset = 1, $length = strlen($str); $offset < $length; $offset += 2) {
    $str[$offset] = ' ';
}
echo $str;

Output:

h l o o l 
---
h l o o l 
---
h l o o l 
  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions