Don't allow toll free numbers in php preg_match regexp - php

Hi am working on some maintenance project. But on that code someone added the preg_match expression for not allowing the toll free numbers.. Toll free numbers start with area codes 800, 888, 877, 866, 855 or 844. They will be formatted as 800-xxx-xxxx or 1-800-xxx-xxxx or (800) xxx-xxxx or 800xxxxxxx or 1800xxxxxxx. etc.
If the number is a toll free number, throw an error "Please enter a local phone number here, not a toll free number."
Below is my code:-
$getphone = $_POST['phone'];
/* ISSUE: This catches
1-800-450-7006
1 (800) 450-7006
1(800) 450-7006
but is not catching
(800) 450-7006
*/
if(!preg_match('/^(?!(?:1-)?(\\$|#|8(00|55|66|77|88)))\(?[\\s.-]*([0-9]{3})?[\\s.-]*\)?[\\s.-]*[0-9]{3}[\\s.-]*[0-9]{4}$/', $getphone)){
// Need to redirect back, not to profile
echo 'Please enter a local phone number here, not a toll free number'; die;
}
Can anyone help me how to check for this case (800) 450-7006. Thanks

I suggest "excluding" specific numbers inside (or not) parentheses at the start:
'~^(?!(?:1-)?(?:\$|#|(?:\((8(?:00|55|66|77|88))\)|(?1))))\(?[\s.-]*([0-9]{3})?[\s.-]*\)?[\s.-]*[0-9]{3}[\s.-]*[0-9]{4}$~'
See the regex demo
I replaced 8(00|55|66|77|88) with (?:\((8(?:00|55|66|77|88))\)|(?1)), a non-capturing group matching two alternatives:
\((8(?:00|55|66|77|88))\) - (, 800, 855, 866, 877, 888 and then )
| - or
(?1) - the whole 8(?:00|55|66|77|88), Group 1, pattern.

<?php
/* 800, 888, 877, 866, 855 or 844. They will be formatted as
800-xxx-xxxx or 1-800-xxx-xxxx or (800) xxx-xxxx or
800xxxxxxx or 1800xxxxxxx */
$phone = $_POST['phone'];
// remove everything that is not a number
$phone = preg_replace('/[^\d]/', '', $phone);
// look for your pattern in the "cleaned" string
if(!preg_match('/^1?8(88|77|66|55|44|00)/', $phone)){
echo 'error';
}
?>

Related

How to remove set off string in PHP [duplicate]

This question already has answers here:
How to remove a substring from a string using PHP?
(4 answers)
Closed 7 years ago.
I have this string variable in my PHP code:
I am getting this value from DB.
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
How to remove this sentence ('Kindly Note: Before 72Hrs Cancellation full refund') from the string.
I have to remove the text which come after this text('Kindly Note:') from the given string How to do that.
Some time I get different text after this text('Kindly Note: We dont allow 24hrs checkin') So I want to remove text whatever comes after this text('Kindly Note:');
Since I love exploding things...try this logic, will remove anything beyond the "Kindly Note:" part:
$includes = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$arr_includes = explode('Kindly Note:', $includes);
$include = $arr_includes[0];
output:
~ All taxes~ Complimentary Buffet Breakfast,~ Complimentary Wi-Fi~ Complimentary Fruit Basket only for Suite RoomFacilities and Services:~ 24Hrs Room Service~ Lounge~ Direct Dialing STD and ISD facilities
use chop()
echo chop($includes,'Before 72Hrs Cancellation full refund');
or
echo chop($includes,'Kindly Note:<br/>Before 72Hrs Cancellation full refund');
Edit 1
use
echo substr($includes, 0, strpos($includes, "Kindly Note:"));
Use str_replace simply.
str_replace('Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $includes);
Simple:
if ($dbText === 'your text') {
$dbText = 'your replacement text';
}
or change the text in the database itself. If you need something else, please elaborate on your requirements. Things like string replacement or regular expression replacement come to mind for more generic problems.
If it comes always end of the string the you can use
substr($string, 0, -3);
use str_replace function
$s = "~ All taxes<br/>~ Complimentary Buffet Breakfast,<br/>~ Complimentary Wi-Fi<br/>~ Complimentary Fruit Basket only for Suite Room<br/><br/>Facilities and Services:<br/>~ 24Hrs Room Service<br/>~ Lounge<br/>~ Direct Dialing STD and ISD facilities <br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund";
$new_string = str_replace('<br/>Kindly Note:<br/>Before 72Hrs Cancellation full refund', '', $s);
Assume "Kindly Note:" exists in the string and you want to remove anything after the "Kindly Note:"
echo strstr($includes, "Kindly Note:", true);

Solving 140 characters Twitter status limit with PHP regex

So, my text I want to post on Twitter is sometimes more than 140 character, so, I need to check the lenght and then go without changes if less than 140 or slive the text into two pieces (the text and the link) and grab the text part and make it e.g. 100 characters long - chop the rest.
Then grab the - now 100 characters long part - and put it otgether with the url.
How to do that?
my code so far:
if (strlen($status) < 140) {
// continue
} else {
// 1. slice the $status into $text and $url (every message has url so
// checking is not important right now
// 2. shorten the text to 100 char
// something like $text = substr($text, 0, 100); ?
// 3. put them back together
$status = $text . ' ' . $url;
}
How should I change my code? I have biggest problem with the first part when getting the url and text part.
Btw. in each $status is only 1 url, so checking for mulitple urls is not necessary
Example of a text that is longer than it should be:
What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador's ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador
should become in the end this:
What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated int https://en.wikipedia.org/wiki/Ecuador
If you can be sure that the URL does not contain any spaces (no well-formed URL should) and that it is always present, try it like that:
preg_match('/^(.*)(\\S+)$/', $status, $matches);
$text = $matches[1];
$url = $matches[2];
$text = substr($text, 0, 100);
But possibly the length of the text should be adapted to the length of the url, so you would use
$text = substr($text, 0, 140-strlen($url)-1);
$reg = '/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i';
$string = "What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador's ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador";
preg_match_all($reg, $string, $matches, PREG_PATTERN_ORDER);
$cut_string = substr($string, 0, (140-strlen($matches[0][0])-1));
$your_twitt = $cut_string . " " . $matches[0][0];
echo $your_twitt;
// ouputs : "What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into t https://en.wikipedia.org/wiki/Ecuador"
This might be what you want :
$status = 'What is now Ecuador was home to a variety of indigenous groups that were gradually incorporated into the Inca Empire during the fifteenth century. The territory was colonized by Spain during the sixteenth century, achieving independence in 1820 as part of Gran Colombia, from which it emerged as its own sovereign state in 1830. The legacy of both empires is reflected in Ecuador\'s ethnically diverse population, with most of its 15.2 million people being mestizos, followed by large minorities of European, Amerindian, and African descendant. https://en.wikipedia.org/wiki/Ecuador';
if (strlen($status) < 140) {
echo 'Lenght ok';
} else {
$totalPart = round(strlen($status)/100);
$fulltweet = array();
for ($i=0; $i < $totalPart; $i++) {
if($i==0)
{
$fulltweet[$i] = substr($status, 0,100);
}else{
$fulltweet[$i] = substr($status, $i * 100);
}
}
}
If the string is longer than 140 chars then it'll explode it in an array of 100 char for each row

Regex PHP, Find characters in specific position

I explain my problem : I'm working on different kind of address
" 25 Down Street 15000 London "
" 25 B Down Street 15000 London "
" Building A 25 Down Street 15000 London "
I found a way to determine which is the number of the street on all case with this regex :
`^([1-9][0-9]{0,2}(?:\s*[A-Z])?)\b`
But now i got a problem that i can't solve, i need when the case is real to determine characters which are before the street's number .
Example : " Building 2 25 Down Street 15000 London " i need here to find only "Building 2"
I understand that i have to find characters before the first number of this string.
Keep searching on my own but will be great if someone got a solution for me .
Thank you .
Edit my code now is :
preg_match('/^(.*?)\d+\s+\D+/', $cleanAdressNode, $result, PREG_OFFSET_CAPTURE,0);
print $result[0][0];
return $result[0][0];
and the result now is : Résidence Les Thermes 1 15 boulevard Jean Jaurès instead of only : Résidence Les Thermes 1
How about:
preg_match('/^(\D*)/', $str, $match);
You will find in $match[1] everything that is not a digit at the begining of the string.
According to your example:
preg_match('/^(.*?)\d+\s+\D+/', $str, $match);
If you only want to match the first non-numeric characters, ^([^0-9]*) should do the trick. It uses class negation to grab every non-numeric characters at the start of the string.

PHP preg_match() in mobile number

How to make preg_match() in mobile number that only accepts:
"+" , "63" , "+63" , "09" at start ,
and a "-" than can be placed between the number?
The number should cointain only 1 "+" and at the beginning.
The "-" should be placed anywhere between the number but only once.
Limitations on 09, 63, and + 63? On 09,
Only exact 11 digits is possible including 09.
On 63, only exact 12 digits is possible including 63.
On +63, only exact 13 digits is possible including +63.
Example:
+639164455539
639164455539
09164455539
0916-4455539
Here's my code:
form name="myform" id="myform" method="post" action="index.php">
<input type="text" id="mobile" name="mobile" placeholder="Input mobile number"> <br /><br /><br />
<?php
$mobile = $_POST['mobile'];
if (isset($_POST['submit_btn'])) {
$submit = $_POST['submit_btn'];
if (preg_match("/^(09|63)[\d]{9}$/m", $mobile)) {
// valid mobile number
echo $mobile;
}
else{
echo "ERROR!";
}
}
?>
<br />
<input type="submit" id="submit_btn" name="submit_btn" value="Submit!">
</form>
try this:
if (preg_match("/^\+(09|63)-?[\d]{9}$/m", $mobile)) {
// valid mobile number
echo $mobile;
}
Demo
Try this regular expression:
/^(?:09|\+?63)(?:\d(?:-)?){9,10}$/m
It matches all examples in the updated question
See http://regex101.com/r/bS0tW2
With the added requirement of "at most one hyphen" we get
/^(?:09|\+?63)(?!.*-.*-)(?:\d(?:-)?){9,10}$/m
The negative look ahead says "from this point forward you cannot match two hyphens".
Updated demo:
http://regex101.com/r/pZ4eJ6
Finally - your requirement about number of digits, while not exactly as you stated in your comment, can probably be met with
/^(?:09|\+?639)(?!.*-.*-)(?:\d(?:-)?){9}$/m
Which actually says:
(?:09|\+?639) - start with either 09 or (optional +)639
(?!.*-.*-) - there may not be more than one hyphen in what follows
(?:\d(?:-)?){9} - there must be exactly 9 digits in what follows; don't count a (single) hyphen
Demo at http://regex101.com/r/zQ5lU8
If you really need exactly what you said, you need to make a bigger "or" statement. Something like this:
^((?:09)(?!.*-.*-)(?:\d(?:-)?){9}$|^\+?63(?!.*-.*-)(?:\d(?:-)?){10}$)
This basically splits the expression in two: either "one starting with the international access code", or "one that doesn't". I don't think it is better because I'm pretty sure that your "international" mobile number always starts with +639, so validating that specific sequence is better for detecting a valid mobile number. However, I just read that for the Philippines
Mobile phone area codes are three digits long and always start with
the number 9, although recently new area codes have been issued with 8
as the starting digit, particularly for VOIP phone numbers.
You might want to consider that as you create your validation...
Hope this will help you. I think you can make even shorter.
$yournumber="+639164455539";
if (preg_match_all("/(^\+?63(?!.*-.*-)(?!.*\+.*\+)(?:\d(?:-)?){10,11}$)|(^09(?!.*-.*-)(?!.*-.*-)(?:\d(?:-)?){9}$)/",$yournumber))
{
echo "Valid";
}
else
{
echo "Invalid number";
}

PHP: How to find the beginning and end of a substring in a string?

This is the content of one mysql table field:
Flash LEDs: 0.5W
LED lamps: 5mm
Low Powers: 0.06W, 0.2W
Remarks(1): this is remark1
----------
Accessories: Light Engine
Lifestyle Lights: Ambion, Crane Fun
Office Lights: OL-Deluxe Series
Street Lights: Dolphin
Retrofits: SL-10A, SL-60A
Remarks(2): this is remark2
----------
Infrared Receiver Module: High Data Rate Short Burst
Optical Sensors: Ambient Light Sensor, Proximity Sensor, RGB Color Sensor
Photo Coupler: Transistor
Remarks(3): this is remark3
----------
Display: Dot Matrix
Remarks(4): this is remark4
Now, I want to read the remarks and store them in a variable. Remarks(1), Remarks(2), etc. are fixed. 'this is remark1', etc. come from form input fields, so they are flexible.
Basically what I need is: Read everything between 'Remarks(1):' and '--------' and save it in a variable.
Thanks for your help.
You can use regex:
preg_match_all("~Remarks\(([^)]+)\):([^\n]+)~", $str, $m);
As seen on ideone.
The regex will put X in match group 1, Y in match group 2 (Remarks(X): Y)
This would be a job for regular expressions, which allow you to match on exactly the kinds of rules your requirements express. Here is a tutorial for you.
Use preg function for this or otherwise you can explode and implode function to get correct result. Don't Use Substring it may not provide correction.
Example of Implode and Explode Function for your query string :
$sdr = "Remarks(4): this is remark4";
$sdr1 = explode(":",$sdr);
$frst = $sdr1[0];
$sdr2 = array_shift($sdr1);
$secnd = implode(" ", $sdr1);
echo "First String - ".$frst;
echo "<br>";
echo "Second String - ".$secnd;
echo "<br>";
Your Answer :
First String - Remarks(4)
Second String - this is remark4

Categories