Jump to content

reformatting a string; need a variable for each array member?


peteschulte

Recommended Posts

I want to write a function that for starts will take a credit card number and put a space between each digit, and also put a period after each group of four digits. (This improves text-to-speech rendering in our Voxeo IVR platform.) My first php file did this by declaring 16 variables, one for each digit. then adding them all with spaces and periods into one new variable which I returned to the TTS engine. For example, $digit_1 = $str[0],  $digit_2 = $str[1], etc. Please, describe a better way to add to or replace members of the string without declaring variables--or a control structure that will create the variables all in one statement. I don't think we need a variable for each char in the string.

We will want to use this function in other contexts where we replace members of the string instead of add to it. the idea is a function to which we pass the original string and a string loaded with pound signs except where we want the new characters to be.

That batch of variables is so clunky, if I could just get a way around that I would feel much better.

Thanks!

 

<?php
///////////////////////////////////////////
//
//	Designer expresses data variables as TEXT STRING, DIGITS and NUMERIC
//	The other types such as  DATE are not fit for our needs with credit cards.
//	DIGITS and ALPHANUMERIC	have the formatting problem already noticed.
//	TEXT STRING is spoken really fast, but without breaks.
//	So this script adds spaces between the digits.
//
///////////////////////////////////////////
$cc_number = trim($_REQUEST['cc_number']);
//	echo $cc_number;
//	$cc_number = '1234567890123456';
//	echo 'The number is ' . $cc_number . '<br/>';
/*
"Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose."
Start with $str[0].
*/

$digit_1 = $cc_number[0]; 
$digit_2 = $cc_number[1];
$digit_3 = $cc_number[2];
$digit_4 = $cc_number[3];
$digit_5 = $cc_number[4];
$digit_6 = $cc_number[5];
$digit_7 = $cc_number[6];
$digit_8 = $cc_number[7];
$digit_9 = $cc_number[8];
$digit_10 = $cc_number[9];
$digit_11 = $cc_number[10];
$digit_12 = $cc_number[11];
$digit_13 = $cc_number[12];
$digit_14 = $cc_number[13];
$digit_15 = $cc_number[14];
$digit_16 = $cc_number[15];	
//	echo "Here is the last digit<br/>" . $digit_16;
//	echo "<br/>Here are the middle digits<br/>" . $digit_7 . $digit_8;

$formattedNumber = $digit_1 . ' ' . $digit_2 . ' ' .$digit_3 . ' ' . $digit_4 . '. ' . $digit_5 . '. ' . $digit_6 . '. ' . $digit_7 . '. ' . $digit_8 . '. ' . $digit_9 . ' ' . $digit_10 . ' ' . $digit_11 . ' ' . $digit_12 . ' ' . $digit_13 . ' ' . $digit_14 . ' ' . $digit_15 . ' ' . $digit_16;
echo $formattedNumber;
// echo '<br/>The formatted number is ' . $formattedNumber;
?>

Link to comment
Share on other sites

thank you ken. Cool. I will look up implode() though it's apparent what it's doing here. What value is in $grp and how did it get there or is $grp a constant?

Mostly I'm grateful to get away from those individual variables!

 

The function I'm writing will also have to take a string such as "conf.dbf" and convert it into "auth.dbf". We're thinking of the function having two parameters, the first one being the original string, for example conf.dbf. The second parameter will indicate which characters to leave in the return string using a pound sign like this auth####.

 

I'm thinking that this string formatting function will need if, else or case depending on whether it's inserting or replacing or doing some other formatting.

Link to comment
Share on other sites

Ken, could it be that the line below the comment here in your code needs to be in a for loop?

<?php
$cc_number = '1234567890123456';
echo '<br/>' . $cc_number . '<br/>';
// the following line breaks it
$cc4 = str_split($cc_number,4);
foreach($cc4 as $i => $grp)
$cc4[$i] = implode(' ',str_split($grp));
echo implode('.',$cc4);
?>

thanks for your reply! I'll pick it up tomorrow.

Link to comment
Share on other sites

Got it! Or . . .

Please revise my comments to identify what the code does or explain it in your reply.

Thanks

 

// echo 'declare a function named say whose parameter is stored as an array in variable $chars';

function say($chars = array())

{

// create the return variable and set it empty

$str = null;

// create the variable with the original string to be inserted into, and load the alphabet into it

$alphabeth = range('a','z');

// accumulate characters and spaces in the return variable

// for as long as $chars has members get each into $char

    foreach($chars as $char)

    // if the next element of $char == negative one, add a space, else add the next array member of the base string

    { $str .= $char==-1 ? ' ' : $alphabeth[$char]; }

    return $str;

    }

 

/* call the function with a parameter which converts into an array

members of the alphabet identified by each one's numerical place

and inserts a space by using a negative one */

echo say(array(7,4,11,11,14,-1,22,14,17,11,3));

 

// Output: hello world

 

Link to comment
Share on other sites

I don't understand what you're asking.  Is there something wrong with your code?  You have comments, so why do you need explanation?  What does this have to do with your other question? If you want some help, you're going to have to give us a motivation and a specific problem, otherwise, it sounds like you're asking us to do your homework or your job for you.

Link to comment
Share on other sites

Here's another way to do it with chunk_split and without arrays:

 

<?php
$cc = "1234123412341234";
echo ltrim(chunk_split(" ".rtrim(chunk_split($cc,1," ")),8,"."));
// output: 1 2 3 4. 1 2 3 4. 1 2 3 4. 1 2 3 4.
?>

 

Yours adds an extra "." on the end though. :o

Link to comment
Share on other sites

Hey Coach!

Here's the latest. Now for a "replace" function to go with it.

thanks for the help. This thread can be closed. See you in another  8)

 

<?php
function formatString($originalChars, $countPlaces, $addChar)
{
$return_str = null;
echo $return_str = ltrim(rtrim(chunk_split($originalChars, $countPlaces, $addChar)));
}

/* 	CODE FOR TESTING
echo 'formatString(\'1234123412341234\',1,\' \') returns ';
$firstReturn = formatString('1234123412341234',1," ");
echo $firstReturn . '<br/>';

echo '<br/>' . 'formatString(\'1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 \',8,\'.\') returns';
$secondReturn = formatString('1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 ',8,".");
echo $secondReturn . '<br/>' . 'end';
END	CODE FOR TESTING */

?>

Link to comment
Share on other sites

thanks for your help along the way! ;)

<html>

<head>

<title>Merge Strings</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

</head>

 

<body>

<?php

//////////////////////////////////

//

// operand1 is a string in the form of 1234567890123456 to be transformed

// operand2 contains digits or sentences fragments to be added to operand1

// where | means leave the original in operand1

//

//////////////////////////////////

 

$operand1 = $_REQUEST['operand1'];

$operand2 = $_REQUEST['operand2'];

 

$i = 0;

$j = 0;

$result = "";

while (strlen($operand1) > $i) {

if ($operand2[$j] == "|")

{

$result = $result . $operand1[$i];

$j ++ ;

$i ++ ;

}

  else

{

$result = $result . $operand2[$j];

$j ++ ;

}

if (strlen($operand2) == $j) $j = 0;

}

while (strlen($operand2) > $j) {

if ($operand2[$j] <> "|") $result = $result . $operand2[$j];

$j ++ ;

}

$return = $result;

 

echo $return;

return $return;

/*

Test using something like

http://yourserver/folder/?operand1=ORIGINAL-STRING&operand2=MERGE-STRING-WITH-PIPE-SYMBOLS

http://web.afts.com/php/mergeStrings.php?operand1=12&operand2=|hi%20there|%20|%20|

and

echo '$operand1      ' . $operand1 . '<br/><br/>';

echo '$operand2      ' . $operand2 . '<br/><br/>';

prints:

$operand1 12

 

$operand2 |hi there| | |

 

1hi there2

*/

 

?>

</body>

</html>

Link to comment
Share on other sites

this is a general purpose function I use for formating things like phone numbers, product codes etc, but it also works for you CC numbers

 

<?php
function format_template($str, $template) {
    $str = str_replace(' ', '', $str);
    $kt = strlen($template);
    $ks = strlen($str);
    $res = '';
    $j = 0;
    for($i=0; $i<$kt; $i++) {
        if ($j==$ks) break;
        switch ($c = $template{$i}) {
            case '#':
                $res .= $str{$j++};
                break;
            case '!':
                $res .= strtoupper($str{$j++}) ;
                break;
            default:
                $res .= $c;
                break;
        }
    }
    return $res;
}

    /**
    * try it
    */
echo format_template ('12345678901234', '(###) ###-#### ext ####');  // --> (123) 456-7890 ext 1234  
echo '<br />';
    
echo format_template ('07123456789', '+44 (#)### ### ####');        // -->  +44 (0)712 345 6789 
echo '<br />';
    
echo format_template ('ab123456x', '!! ## ## ## !');                // -->  AB 12 34 56 X
echo '<br />';
    
echo format_template ('1234567823456789', '# # # # . # # # # . # # # # . # # # #'); // 1 2 3 4 . 5 6 7 8 . 2 3 4 5 . 6 7 8 9

 

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.