How to delete the first digit number in PHP - php

I have a data of phone number starts with +63 and 09
for example the user insert 09123456789 then save. The user shouldn't success if he enters +639123456789 because it was same number at all.
I tried using substr_replace
$data3 = substr_replace("+63", "0",0, 3);
is there other option? i think the substr_replace will have error in the future.
thanks

If the +63 must be at the start, you may use a preg_replace like
$s = preg_replace('~^\+63~', '0', $s);
Here,
^ - start of a string position
\+ - a literal +
63 - a 63 substring.
See the regex demo and a PHP demo.
Please also consider Tpojka's suggestion to use a combination of intl-tel-input on front-end and libphonenumber-for-php on back-end if you need to sanitize and validate international phone numbers.

In this case you can have a condition to check and have str_replace
if there is a + on your request then make remove the first 3 letters including +
if (substr($phone, 0, 1) == '+') {
$phone = str_replace(substr($phone, 0, 3), '0', $phone);
}
$phone_number = $phone;

Related

Preg_matching email and looking for specific text

I have a bunch of emails that I read as text in my program and they all have phone numbers such as these:
+370 655 54298
+37065782505
37069788505
865782825
65782825
(686) 51852
How would I go about finding them and saving it into a variable?
For now I am doing it like this:
$found = preg_match('^[0-9\-\+]{9,15}^', $text, $num);
But it does not working at all
Have a look at the "libphonenumber" Google Library.
There are two functions you may find useful
isPossibleNumber - quickly guessing whether a number is a possible phonenumber by using only the length information, much faster than a full validation.
isValidNumber - full validation of a phone number for a region using length and prefix information.
This should work https://regex101.com/r/E2PzRN/2
#\+?\(?\d+\)?\s?\d+\s?\d+#
<?php
$regex = '#\+?\(?\d+\)?\s?\d+\s?\d+#';
$x = [
'+370 655 54298',
'+37065782505',
'37069788505',
'865782825',
'hjtgfjtdfjtgdfjt',
'65782825',
'(686) 51852',
];
foreach ($x as $y) {
if (preg_match($regex, $y, $match)) {
echo $match[0] . "\n";
}
}
Check it in action here https://3v4l.org/6AlQa
We distinguish here 3 types of phone numbers.
The first type is this one:
+37065782505
37069788505
865782825
65782825
Here, the beginning + is optional. we thus consider that we have 7 digits minimum for these numbers.
The regular expression obtained is therefore
(\+?[0-9]{7,})
The second type is this one:
+370 655 54298
Here we have a first block consisting of a + followed by 2 to 6 digits and then several other blocks of 2 to 6 digits and separated by spaces.
The regular expression obtained is therefore
(\+[0-9]{2,6}(\s[0-9]{2,6})+)
The last type is this one:
(686) 51852
This is a first block consisting of 2 to 6 digits surrounded by parentheses and then several other blocks of 2 to 6 digits and separated by spaces.
The regular expression obtained is therefore
(\([0-9]{2,6}\)(\s[0-9]{2,6})+)
The complete extraction code is therefore
preg_match_all("#(\+?[0-9]{7,})|(\+[0-9]{2,6}(\s[0-9]{2,6})+)|(\([0-9]{2,6}\)(\s[0-9]{2,6})+)#",$text,$out);
$found = $out[0];
where $found is an array.
I would suggest stripping out '+','(',')',' ' and testing if it is a ctype_digit
remove all characters and test if numeric, this assumes that the result is a phone no, if you were to run this on an email address the result would be false
var_dump(ctype_digit(str_replace([' ', '+', '(', ')'], '', '(686) 51852')));
TRUE
var_dump(ctype_digit(str_replace([' ', '+', '(', ')'], '', 'r#pm.mr')));
FALSE

PHP Strip String, Convert to int

I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.

Replace Leading zero with '+' in PHP

I want to replace the leading zero in a phone number with '+' and country code.
If the phone number starts with zero (ex: 07512345678) then I want to remove the leading zero and replace with '+' and country code else (ex: 7512345678)just add '+' and country code.
What would the way to do that in PHP?
Use preg_replace()
$newNumber = preg_replace('/^0?/', '+'.$countryCode, $phoneNumber);
The first parameter is the regular expression, which is looking for that leading zero of yours. The second is what you want to replace it with (the plus sign concatenated with the country code.). Finally, $phoneNumber is the original phone number.
The replaced value is assigned to the variable $newNumber. Feel free to change the variables to fit your code.
Use substr_replace(), no need for regex or if blocks.
$number = '07512345678';
$country_code = '44';
$new_number = substr_replace($number, '+'.$country_code, 0, ($number[0] == '0'));
You could use preg_replace:
$newNumber = preg_replace("/^0/", "+", 07512345678)
This will replace the first character of each number if and only if it is zero. The regular expression used is: /^0/. The ^ tells it to look at the first character, and then only match a 0 thereafter. This 0 will be replaced with the second argument, the "+". The last argument is the source string.
Reference
Take a look at preg_replace here
Basic syntax for beginning REGEX here
You can use string manipulation:
$x = '012345678';
if ($x[0]=='0') $x[0] = ''; // delete leading zero
$x = '+1'.$x;
preg_match() is less effective I suspect, due to the complexity of the whole system.
<?php
$countryCode = "XX";
$phone = array("0123455", "7837373");
foreach( $phone AS $number ) {
if( $number[0] == '0' ) {
$number = "+{$countryCode}" . substr($number,1);
}
echo "{$number}\n";
}
PS: this is elementary. You should really got through some tutorials.

replacing first few digits with #

I want to hide the first 6 digits of social security
I have them like 123-456-7890
I want to show ###-###-7890
how can I do that
thanks
$ssn = '123-456-7890';
$ssn = '###-###-'.substr ($ssn , 8);
You can use the substr method to get the rightmost 4 characters from the SSN using a negative length:
$ssn = '111-222-4567';
$ssn_obscured = '###-###-' . substr($ssn, -4);
See http://us.php.net/substr for more information on the method.

Splitting text in PHP

I want to know is there any way to split text like this:
123456789 into 123-456-789
as to add "-" after every 3 characters?
Just wanted to know, as I know the reverse, but how to do this is over my head. ;)
and also if the text is
ABCDEFGHI OR A1B2C3D4E or any other format
without any space between the characters !
language: PHP only
<?php
$i = '123456789';
echo 'result: ', wordwrap($i, 3, '-', true);printsresult: 123-456-789
see http://php.net/wordwrap
I'm not a big fan of regexes for simple string extraction (especially fixed length extractions), preferring them for slightly more complex stuff. Almost every language has a substring function so, presuming your input has already been validated, a simple (pseudo-code since you haven't specified a language):
s = substring (s,0,3) + "-" + substring (s,3,3) + "-" + substring (s,6,3)
If you want it every three characters for a variable length string (with odd size at the end):
t = ""
sep = ""
while s != "":
if s.len <= 3:
t = t + sep + s
s = ""
else:
t = t + sep + substring (s,0,3)
s = substring (s,3)
sep = "-"
s = t
For any language:
Create an empty string variable called "result"
Create an integer counter variable, "i", which increments until the length of the original string (the one with the number)
Append each character from the original string to "result"
If i modulo 3 (usually % or mod) is zero, append a dash to "result"
In the interest of completeness, here is a Python solution:
>>> a = "123456789"
>>> a[0:3] + "-" + a[3:6] + "-" + a[6:9]
'123-456-789'
Since you updated your question to specify a PHP solution, this should work:
substr($a, 0, 3) . "-" . substr($a, 3, 3) . "-" . substr($a, 6, 3)
See substr for more information on this function. This will work not only for digits, but for alphabetic characters too.
Yet another Python version:
>>> x="123456789"
>>> out=[x[i:i+3] for i in xrange(0, len(x), 3)]
>>> print "-".join(out)
123-456-789
I think that this can be sanely done in a regex with lookahead:
s/(.{3})(?=.)/$1-/g
Since you mentioned PHP in a comment:
preg_replace ("/(.{3})(?=.)/", "$1-", $string);
edit: After VolkerK showed wordwrap, I found chunk-split in the documentation:
$new_string = chunk_split ($string, 3, '-');
This has the advantage that it also works when there are spaces in the string (wordwrap would prefer to break at the spaces).
In Perl:
#!/usr/bin/perl
use strict;
use warnings;
my $string = "123456789";
$string =~ /(\d{3})(\d{3})(\d+)/;
print "$1-$2-$3"
You can do it with (among other means) a regular expression match and replace. The exact syntax depends on the tool or programming language you are using. For instance, one way to do it in Perl would be
$a = "123456789";
$a =~ s/(\d{3})/$1-/g;
chop($a);
print $a;
Line 2 replaces every 3 digits for the same 3 digits and a dash. With chop() we delete the trailing dash.
There is another question here. What to do when the string doesn't contain a multiple by 3 amount of digits? If such strings were allowed, then the above snippet would need modification.
Also, depending on the specifics of the case, you might get away with simple substring replacement, or string slicing.
One more Perl example. This doesn't remove final groups smaller than three, and it leaves initial groups of less than three digits alone. It's based (pretty shamelessly) on the "money numbers" example in Learning Perl (page 212 of the 5th ed):
#!/usr/bin/env perl
use strict;
use warnings;
print "Gimme' a number: ";
chomp(my $number = <STDIN>);
1 while ($number =~ s/([0-9]{3})([0-9]+)/$1-$2/);
print "Now it's $number\n";

Categories