PHP preg_match() in mobile number - php

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";
}

Related

How to restrict few special characters for address field in PHP without regex?

HTML for address field:
<p> <label for="username">Address:</label>
<input type=text name="address" placeholder="Enter your address">
</p>
I have to check the address entered by the user against these conditions given below:
Only letters, numbers, hash, comma, circular brackets, forward slash, dot and hyphen are allowed.
Starting and ending should not be special characters.
Two consecutive special characters are not allowed.
I think you are looking for html5 input field restrictors. But there exists one only for email address or url address, not for a regular physical address
https://www.w3schools.com/html/html_form_input_types.asp
<form>
E-mail:
<input type="email" name="email">
</form>
<form>
Add your homepage:
<input type="url" name="homepage">
</form>
based on your updated restrictions. This is best done with regular expressions
I have to check the address entered by the user against these
conditions given below: 1) Only letters, numbers, hash, comma,
circular brackets, forward slash, dot and hyphen are allowed. 2)
Starting and ending should not be special characters. 3) Two
consecutive special characters are not allowed.
This is the regex you need
/^([a-zA-Z0-9 ]|[a-zA-Z0-9 ][-#,()\/.])*[a-zA-Z0-9 ]$/gm
https://regex101.com/r/irDQ1S/1
Consider using filter_var()
http://php.net/manual/en/function.filter-var.php
function addressFilter($address)
{
$invalidChars = ['%', '&']; // Array of invalid characters
foreach ($invalidChars as $invalidChar) {
if (strpos($address, $invalidChar) !== false) {
return false;
}
}
return $address;
}
$address = filter_var($_POST['address'], FILTER_CALLBACK, ['options' => 'addressFilter']);

PHP regex preg_match numbers before a multiword string

I am trying to extract the number 203 from this sample.
Here is the sample I am running the regex against:
<span class="crAvgStars" style="white-space:no-wrap;"><span class="asinReviewsSummary" name="B00KFQ04CI" ref="cm_cr_if_acr_cm_cr_acr_pop_" getargs="{"tag":"","linkCode":"sp1"}">
<img src="https://images-na.ssl-images-amazon.com/images/G/01/x-locale/common/customer-reviews/ratings/stars-4-5._CB192238104_.gif" width="55" alt="4.3 out of 5 stars" align="absbottom" title="4.3 out of 5 stars" height="12" border="0" /> </span>(203 customer reviews)</span>
Here is the code I am using that does not work
preg_match('/^\D*(\d+)customer reviews.*$/',$results[0], $clean_results);
echo "<pre>";
print_r( $clean_results);
echo "</pre>";
//expecting 203
It is just returning
<pre>array ()</pre>
Your regexp has two problems.
First, there are other numbers in the string before the number of customer reviews (like 4.3 out of 5 stars and height="12"), but \D* prevents matching that -- it only matches if there are no digits anywhere between the beginning of the string and the number of reviews.
Second, you have no space between (\d+) and customer reviews, but the input string has a space there.
There's no need to match any of the string before and after the part that contains the number of customer reviews, just match the part you care about.
preg_match('/(\d+) customer reviews/',$results[0], $clean_results);
$num_reviews = $clean_results[1];
DEMO

PHP and preg_match Regex to pull number with decimal out of string

Pretty basic stuff here, trying to pull the number 14.5 out of this string using regex and php but I can't seem to get syntax correct. Also, the number is dynamic and may not always be a decimal but the goal here is to try and pull a number between the word Weight: and </li>:
<ul>
<li>Manufacturer: something</li>
<li>Model: 1216D101</li>
<li>Condition: New</li>
<li>Dimensions: 12" x 16"</li>
<li>Sold by the Dozen</li>
<li>Weight: 14.5 Lbs.</li>
</ul>
This is what I have so far and have tried variations but keep falling short:
if (preg_match("/\Weight:\(\d+)\.(\d*?)\<\/li>/", $desc, $WEIGHT) == true)
{ echo $WEIGHT[0]; }
Try this:
if (preg_match('/Weight: (\d+(\.\d+)?)/', $desc, $matches)) {
echo $matches[1];
}
Try this regex:
/Weight: ((?:\d+)(?:\.\d*)?)/
The matched number will be available in $WEIGHT[1].
If you don't want to capture the . in numbers like 123.:
/Weight: ((?:\d+)(?:\.\d+)?)/
preg_match('<li>Weight: (\d+)\.?(\d+)?.+</li>', // ...
Should to the trick
if you JUST want to match a number integer OR decimal
if (preg_match('/^(\d+(\.\d+)?)$/',$num)) echo "$num is integer or decimal";

Extract words between two words with regex

I have a string:
8 nights you doodle poodle
I wish to retrieve every thing between nights and poodle, so in the above example, the output should be you doodle.
I'm using the below regex. Please can someone point out what I may be doing wrong?
if (preg_match("nights\s(.*)\spoodle", "8 nights you doodle poodle", $matches1)) {
echo $matches1[0]."<br />";
}
You're close, but you're accessing the wrong index on $matches1. $matches1[0] will return the string that matched in preg_match();
Try $matches1[1];
Also, you need to enclose your regex in / characters;
if (preg_match("/nights\s(.*)\spoodle/", "8 nights you doodle poodle", $matches1)) {
echo $matches1[1]."<br />";
}
Output
you doodle<br />
You probably want something like this
if (preg_match("/nights\s(.*)\spoodle/", "8 nights you doodle poodle", $matches1)) {
echo $matches1[1]."<br />";
}
Check out rubular.com to test your regular expressions. Here is another relevant question:
Using regex to match string between two strings while excluding strings

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