View Full Version : Put different characters before every char in a string (odd request I know..)
09-23-2005, 12:06 AM
If you have the string "blah blah bleh", I want PHP to put different letters before every letter in the string, so that it ends up looking like "AbBlCaDh EbFlGaHh IbJlKeLh". Then when it gets to Z on the string, I want it to start with A again. I know this is an odd request, but there's a reason :)
09-23-2005, 07:29 AM
Off the top of my head, I'd do it like this:
$letter = 65; //ascii code for 'A'
$str_length = strlen($string); //get length of string for loop
$chars_added = 0; //number of chars we've added to string
for( $i=0;$i<$str_length;$i++ )
$string_place = $i + $chars_added;
//check that you're only adding to a letter,
//not some other char or space
if( preg_match('/[a-zA-Z]/',substr($string,$string_place,1)) )
//convert the letter from ascii and insert into $string
$string = substr_replace($string,chr($letter),$string_place,0);
//increment letter counter
if( $letter == 90) //90 is 'Z'
$letter = 65; //wrap to 'A'
09-23-2005, 07:14 PM
That's excellent.. just what I needed.. thanks :)
Final question.. I need it to add a character before every inserted letter. So it would end up looking like:
-AB-Bl-Ca-Dh -Eb-Fl-Ga-Hh -Ib-Jl-Ke-Lh
Original string is in bold. I have tried:
$string = substr_replace($string,chr(45)chr($letter),$string_place,0);
But it throws an error :/
09-23-2005, 07:29 PM
$string = substr_replace($string,'-' . chr($letter),$string_place,0);
Since it looks like it's the same character every time, we don't need to use ascii. We're ascii-fying the letters because it's a lot easier to increment and wrap the numbers and then convert. You'll also need to change
$chars_added = $chars_added + 2;
Otherwise, $string_place will no longer be accurate, and your inserts won't be where they're supposed to be.
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.