Jump to content

extracting from string


applewilliam

Recommended Posts

The easiest method is a recurring substr function:

 

use a while() loop eg:

 

<?php
$cstring = "hj45ederl840lmcjower oldwsd3ohwxrzswlzswd";
$new_string = substr($cstring,0,1);  // Gets the first letter.
$cstring = substr($cstring,1); // Removes First letter from current string.

while($more_left == true){ // While there is more to do, continue the loop.
   
   // If there is at least 4 characters left (3 to skips and 1 to add), then do this.
   if(strlen($cstring) >= 4){
      $new_string .= substr($cstring,3,1); // Add the fourth letter (skip 3 letters)
      $cstring = substr($cstring,4); // Get rid of that last part so we can continue with the next letter.
   }else{
      $more_left = false; // If there arent enough characters to skip then there must be no characters to save, so break the loop.
   }
}

echo($new_string);
// Untested.

?>

 

That should work. substr is extremely useful.

 

Hope this Helps,

-CB-

Its not perfect but it works

$str = 'hj45ederl840lmcjower oldwsd3ohwxrzswlzswd';
for($i=0;$i<strlen($str);$i+=4) {
echo $str{$i};
}

 

Ok if the string needs to be extracted every 2 letters.  How do I make a variable for this $i+=4.  That can be set

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.