add delimiters to a phone number - php

I need to turn this phone number:
5555555555
into this string with delimiters:
"555.555.5555"
Here's my code:
$phone = 5555555555;
$phoneArray = explode(2, $phone);
print_r($phoneArray);
and it returns this:
Array ( [0] => 555 [1] => [2] => 55555 )
What am I doing wrong?

Lots of ways to do this, and RegEx not required, but here's a nice and easy one w/ RegEx:
$phone = '5555555555';
echo preg_replace('/(\d{3})(\d{3})(\d{4})/', "$1.$2.$3", $phone);
Cheers

You need something more like this:
$number = '123456789';
$segments = array();
$segments[] = substr($number, 0, 3);
$segments[] = substr($number, 3, 3);
$segments[] = substr($number, 6, 4);
$number = implode('.', $segments); // Comes out to 123.456.7890
Note that you'll want to do some format checking first. You'll need to verify
that they actually entered a 10-digit number with no dividing symbols.

You probably don't want to use explode since you don't have a known delimiter within the string to cause the split. You could use str_split($phone,3) which would give you 3 array elements of 3, and a 4th of 1. Keep the first two and merge the final two together into your 3rd array elemnent:
$phone = 5555555555;
$phoneArray = str_split($phone,3);
$phoneArray[2] .= phoneArray[3];
print_r($phoneArray);
Hope that helps.

Related

Substr not allowing double digit codes to process on form

I have an array that uses two codes in a list and pushes them into a form on the next page. Currently I have:
$code= array();
$code['c1'] = substr($part, 0, 1);
$code['c2'] = substr($part, 2);
Now, If I select anything with a single digit c1 and single or double c2 then it adds to the form.
Examples:
1-9
1-15
9-12
9-9
But if I try to add anything with double digits in c1 it doesn't add, like:
10-1
10-2
10-11
If I try
$codes= array();
$codes['c1'] = substr($part, 0, 2);
$codes['c2'] = substr($part, 2);
Then no codes show up.
How can I account for both?
UPDATE:
Currently, the above code, if I select 10-58, will dump c1 as 1 and c2 as -5
You can easily use explode() and list() to split any combination of codes...
$part = "1-15";
$codes = array();
list($codes['c1'], $codes['c2']) = explode("-", $part);
print_r($codes);
gives...
Array
(
[c1] => 1
[c2] => 15
)
For
$part = "10-15";
it gives...
Array
(
[c1] => 10
[c2] => 15
)
If you are unsure if your data is always correct, you can check that the data has 2 components after using explode() and only convert it then, you can also do something to report and error or whatever you need...
$split = explode("-", $part);
if ( count($split) == 2 ){
$codes['c1'] = $split[0];
$codes['c2'] = $split[1];
}
else {
// Not of correct format.
}
print_r($codes);

Isolate substring at end of string after a specific substring

My query generates a result set of UID values which looks like:
855FM21
855FM22
etc
I want to isolate the last number from the UID which it can be done by splitting the string.
How to split this string after the substring "FM"?
To split this string after the sub string "FM", use explode with delimiter as FM. Do like
$uid = "855FM22";
$split = explode("FM",$uid);
var_dump($split[1]);
You can use the explode() method.
<?php
$UID = "855FM21";
$stringParts = explode("FM", $UID);
$firstPart = $stringParts[0]; // 855
$secondPart = $stringParts[1]; // 21
?>
use explode function it returns array. to get the last index use echo $array[count($array) - 1];
<?php
$str = "123FM23";
$array = explode("FM",$str);
echo $array[count($array) - 1];
?>
For it,please use the explode function of php.
$UID = "855FM21";
$splitToArray = explode("FM",$UID);
print_r($splitToArray[1]);
Have you tried the explode function of php?
http://php.net/manual/en/function.explode.php
As a matter of best practice, never ask for more from your mysql query than you actually intend to use. The act of splitting the uid can be done in the query itself -- and that's where I'd probably do it.
SELECT SUBSTRING_INDEX(uid, 'FM', -1) AS last_number FROM `your_tablename`
If you need to explode, then be practice would indicate that the third parameter of explode() should set to 2. This way, the function doesn't waste any extra effort looking for more occurrences of FM.
echo explode('FM', $uid, 2)[1]; // 21
If you want to use php to isolate the trailing number in the uid, but don't want explode() for some reason, here are some wackier / less efficient techniques:
$uid = '855FM21';
echo strtok($uid, 'FM') ? strtok('FM') : ''; // 21
echo preg_replace('~.*FM~', '', $uid); // 21
echo ltrim(ltrim($uid, '0..9'), 'MF'); // 21
$uid = '123FM456';
$ArrUid = split( $uid, 'FM' );
if( count( $ArrUid ) > 1 ){
//is_numeric check ?!
$lastNumbers = $ArrUid[1];
}
else{
//no more numbers after FM
}
You can also use regular expressions to extract the last numbers!
a simple example
$uid = '1234FM56';
preg_match( '/[0-9]+fm([0-9]+)/i', $uid, $arr );
print_r($arr); //the number is on index 1 in $arr -> $arr[1]

How to replace number data within a string to a different number?

There is a string variable containing number data , say $x = "OP/99/DIR"; . The position of the number data may change at any circumstance by user desire by modifying it inside the application , and the slash bar may be changed by any other character ; but the number data is mandatory. How to replace the number data to a different number ? example OP/99/DIR is changed to OP/100/DIR.
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);
print $string;
Output:
OP/100/DIR
Assuming the number only occurs once:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);
To change the first occurance only:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);
Using regex and preg_replace
$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);
print $x;
The most flexible solution is to use preg_replace_callback() so you can do whatever you want with the matches. This matches a single number in the string and then replaces it for the number plus one.
root#xxx:~# more test.php
<?php
function callback($matches) {
//If there's another match, do something, if invalid
return $matches[0] + 1;
}
$d[] = "OP/9/DIR";
$d[] = "9\$OP\$DIR";
$d[] = "DIR%OP%9";
$d[] = "OP/9321/DIR";
$d[] = "9321\$OP\$DIR";
$d[] = "DIR%OP%9321";
//Change regexp to use the proper separator if needed
$d2 = preg_replace_callback("(\d+)","callback",$d);
print_r($d2);
?>
root#xxx:~# php test.php
Array
(
[0] => OP/10/DIR
[1] => 10$OP$DIR
[2] => DIR%OP%10
[3] => OP/9322/DIR
[4] => 9322$OP$DIR
[5] => DIR%OP%9322
)

REGEX with PHP on File Name

I am atempting to extract the sort code and account number from a filename given that the first 6 figures represent the sort code and the last 8 figures represent the account number. An example of the filename would be:
./uploads/Santander/Statement_01020387654321.qif
What I have written does not seem to work, as I am new to regex maybe someone can explain how this should be done, or where I have gone wrong.
$sort = '';
$acno = '';
$ret = preg_match('/Statment_[0-9]{14}\.(csv|qif|qfx|ofx)$/', $file);
if ($ret)
{
if (ereg ('/_[0-9]{14}\./', $file, $regs))
{
$reg = $regs[count($regs)-1];
$sort = substr($reg, 1, 6);
$acno = substr($reg, 7, 8);
}
}
I'm sure somebody versed with regular expressions can help you out, but it's possible without as well. It may be the more attractive option in the long run, because it's easier to maintain.
$path = "./uploads/Santander/Statement_01020387654321.qif"
$filename = pathinfo($path, PATHINFO_BASENAME); // "Statement_01020387654321.qif"
$temp_array = explode("_", $filename);
$sortcode = substr($temp_array[1], 0, 6); // 010203
$account = substr($temp_array[1], 6, 8); // 7654321
Do it in the first step of matching:
$ret = preg_match('/Statement_([0-9]{6})([0-9]{8})\.(csv|qif|qfx|ofx)$/', $file, $matches);
And in $matches you have info about sort number, account number and extension.
tested
echo $file ='./uploads/Santander/Statement_01020387654321.qif';
$ret = preg_match('/Statement_(\d{6})(\d{8})\.(csv|qif|qfx|ofx)$/', $file, $matches);
echo "<pre>";
print_r($matches);
returns
Array
(
[0] => Statement_01020387654321.qif
[1] => 010203
[2] => 87654321
[3] => qif
)
I think you just spelled "Statement" wrong in your Regex
In your Regex its: "Statment" without an "e"

Most efficient way to delimit key

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
Use str_split():
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
The output:
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
This is a bit more general:
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>

Categories