Phone Number Regex Conditions - php

I need to create a regex function to check phone numbers entered on a phone number field based on these conditions.
• if the number starts with either 6, 8 or 9 and another 7 digits
• or if the number starts with either +656, +658 or +659 and another 7 digits
So basically its singapore phone number with +65 being the country code
6, 8 or 9 are the only starting digit of phone numbers.
I have tried code below but it wont work.
add_filter( 'gform_phone_formats', 'sg_phone_format' );
function sg_phone_format( $phone_formats ) {
$phone_formats['sg'] = array(
'label' => 'Singapore',
'mask' => false,
'regex' => '/^[689]\d{7}$/D|/^(\+656)\d{7}$/D|/^(\+658)\d{7}$/D|/^(\+659)\d{7}$/D',
);
return $phone_formats;
}
Thank you!

I would use this regex pattern for Singapore numbers:
^(?:\+65)?[689][0-9]{7}$
Sample script:
$number = "+6587654321";
if (preg_match("/^(?:\+65)?[689][0-9]{7}$/", $number)) {
echo "MATCH";
}

So basically the set condition for a regex match can be found by alternating a grouping of sets that match the occurrences of the desired character or number, like so:
<code>
//$regex = '/\+65+[?:6?8:?:9]+[0-9]{3}+[0-9]{4}/'; //wrong
// Edited the following lines
$regex = '/(?:\+65[6|8|9]+[\d]{7})|(?:\+65[689][\-|\s|\/][0-9]{3}+[\-|\s|\/][0-9]{4})/';
$phone = '+6561234567,+6587654321,+659-432-1567,+6594321567,+659 765 4321,+658/765/1234,+659--432--1567,+6555?:?1231234'; //test string
//Match $var against a regular expression
preg_match_all($regex, $phone, $matches, PREG_SET_ORDER, 0);
//var_dump
var_dump($matches) . " \n";
//print_r
print_r ($matches) . " \n";
//echo single value array();
echo $matches[0][0];
echo "<br />";
echo $matches[1][0];
echo "<br />";
echo $matches[2][0];
echo "<br />";
echo $matches[3][0];
echo "<br />";
echo $matches[4][0];
echo "<br />";
echo $matches[5][0];
echo "<br />";
echo $matches[6][0];
</code>
The result from the above code is as follow:
<pre>
//var_dump
array(6) { [0]=> array(1) { [0]=> string(11) "+6561234567" } [1]=> array(1) { [0]=> string(11) "+6587654321" } [2]=> array(1) { [0]=> string(13) "+659-432-1567" } [3]=> array(1) { [0]=> string(11) "+6594321567" } [4]=> array(1) { [0]=> string(13) "+659 765 4321" } [5]=> array(1) { [0]=> string(13) "+658/765/1234" } }
//print_r
Array ( [0] => Array ( [0] => +6561234567 ) [1] => Array ( [0] => +6587654321 ) [2] => Array ( [0] => +659-432-1567 ) [3] => Array ( [0] => +6594321567 ) [4] => Array ( [0] => +659 765 4321 ) [5] => Array ( [0] => +658/765/1234 ) )
//echo single value array();
+6561234567
+6587654321
+659-432-1567
+6594321567
+659 765 4321
+658/765/1234
</pre>
You can easily match more personalized regular expressions by setting specific conditions to match the string by escaping additional characters with
\ or any whitespace character with
\s
<code>
// add more characters to regex to match +659-432-1567
$regex = '/\+65[6|8|9]+[\-][0-9]{3}+[\-][0-9]{4}/';
</code>
The result from the modified regular expression will be
<pre>
array(1) { [0]=> array(1) { [0]=> string(13) "+659-432-1567" } }
Array ( [0] => Array ( [0] => +659-432-1567 ) )
+659-432-1567 //echo one match out of six
</pre>

Related

PHP Why two same value from two different string are not equal to each other

Why are these two strings not equal?
I tried to get the same name so I can create a file, however I cannot get two strings equal to each other, even though I think both strings have the same value.
I uploaded var_dump output
any idea how to fix it?
$selectCategory = scandir($_SERVER['DOCUMENT_ROOT'].'/database/');
$cat = explode('.',$category);
print_r($cat);
print_r($selectCategory);
if($cat[0] == $selectCategory[2]){
echo " true";
}
else{
echo "no";
}
output:
Array ( [0] => bus [1] => php )
Array ( [0] => . [1] => .. [2] => bus [3] => fruit )
no
This is var_dump output
array(2) { [0]=> string(5) " bus" [1]=> string(3) "php" }
array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "bus" [3]=> string(5) "fruit" }
no
As you can see from the var_dump output the items you are comparing are different lengths. There is a space and possibly a hidden character in the $cat one:
To trim all space and some other characters use this:
$cat = array_map('trim', $cat);
$selectCategory = array_map('trim', $selectCategory);

Iterating through Array of Arrays generating unwanted output

I am having issues when iterating through an array of arrays in PHP.
I have the following array, which I have posted to the page using Ajax.
Array (
[0] => Array ( [0] => T64 [1] => Array ( [name] => T64 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[1] => Array ( [0] => T65 [1] => Array ( [name] => T65 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[2] => Array ( [0] => T91 [1] => Array ( [name] => T91 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) ) )
I have tried to print all of the inner values using the below method, however it always prints a T (on its own line), before each desired value.
foreach($sOptions as $row => $innerArray){
foreach($innerArray as $innerRow => $value){
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}
}
Output:
T
T
T
2
2
2
T
T
T
2
2
2
T
T
T
2
2
2
Would anyone be able to give be some incite to where these T values are coming from?
It is obvious. You are trying to get indexed value of the actual value from second level array using a string index that does not exists.
Because any string can be accessed as an array then the non existing string index is interpreted as false so it returns first value, ie zero-index character from the string accessed as an array.
In first case the value T64 is actually accessed as array('T','6','1') so it returned T.
<?php
// simple example
// Get the first character of a string
$str = 'T64';
echo "First character is: ". $str[0] .PHP_EOL;
echo "Second character is: ". $str[1] .PHP_EOL;
echo "Third character is: ". $str[2] .PHP_EOL;
echo PHP_EOL;
echo "Applied to your code:". PHP_EOL;
$sOptions = Array ( Array ( 'T64' ) );
print_r($sOptions[0][0]['invalid string index']);
Look at the demo: https://eval.in/1063420
Output:
First character is: T
Second character is: 6
Third character is: 4
T
Note: turn on error reporting to simplify your debugging ;) How do I get PHP errors to display?
More reading about accessing strings as array in described in PHP manual Strings esspecialy Example #11 and later.
can you try to use only one foreach ? I haven't try this solution but you can try to do something of similar
foreach($sOptions as $row => $innerArray){
$value = $innerArray[1]
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}
You can also use array_column to isolate the part you want to iterate.
foreach(array_column($arr,1) as $row => $value){
echo $value['dummyA'] . "\n";
echo $value['dummyB'] . "\n";
echo $value['dummyC'] . "\n";
}
This means the code will only iterate the following:
array(3) {
[0]=>
array(4) {
["name"]=>
string(4) "T64 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
[1]=>
array(4) {
["name"]=>
string(3) "T65"
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(1) "2"
}
[2]=>
array(4) {
["name"]=>
string(4) "T91 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
}
https://3v4l.org/YA6Vq

PHP - Splitting string lines up into two variables

Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:
Lambo 1; Trabant 2; Car 3;
Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.
As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
$element = trim($element);
if (strpos($element, " ") !== false ) {
list($car, $number) = explode(" ", $element);
echo "car: $car, number: $number";
}
}
You can use explode to split the input on each ;, loop over the results and then split over each .
You can use preg_split and iterate over the array by moving twice.
$output = preg_split("/ (;|vs) /", $input);
You could use preg_match_all for getting those parts:
$line = "Lambo 1; Trabant 2; Car 3;";
preg_match_all("/[^ ;]+/", $line, $matches);
$matches = $matches[0];
With that sample data, the $matches array will look like this:
Array ( "Lambo", "1", "Trabant", "2", "Car", "3" )
$new_data="Lambo 1;Trabant 2;Car 3;" ;
$new_array=explode(";", $new_data);
foreach ($new_array as $key ) {
# code...
$final_data=explode(" ", $key);
if(isset($final_data[0])){ echo "<pre>".$final_data[0]."</pre>";}
if(isset($final_data[1])){echo "<pre>".$final_data[1]."</pre>";}
}
This places each word and number in a new key of the array if you need to acess them seperatly.
preg_match_all("/(\w+) (\d+);/", $input_lines, $output_array);
Click preg_match_all
http://www.phpliveregex.com/p/fM8
Use a global regular expression match:
<?php
$subject = 'Lambo 1; Trabant 2; Car 3;';
$pattern = '/((\w+)\s+(\d+);\s?)+/Uu';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output you get is:
array(4) {
[0] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[1] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[2] =>
array(3) {
[0] =>
string(5) "Lambo"
[1] =>
string(7) "Trabant"
[2] =>
string(3) "Car"
}
[3] =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "2"
[2] =>
string(1) "3"
}
}
In there the elements 2 and 3 hold exactly the tokens you are looking for.

php return an empty array after foreach

Can I avoid the empty array that generate by foreach ?
here is my code
$file="test.txt";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
foreach($lines as $line){
$domain = preg_split('/\s+/', $line,-1,PREG_SPLIT_NO_EMPTY);
echo "<pre>";
var_dump($domain);
echo "$domain[0] OK";
echo "</pre>";
}
test.txt contains this
www.google.com 2.2.2.3
www.test.com 2.2.2.3
www.example.com 2.2.2.3
after I ran my script the result is this
array(2) {
[0]=>
string(14) "www.google.com"
[1]=>
string(7) "2.2.2.3"
}
www.google.com OK
array(2) {
[0]=>
string(12) "www.test.com"
[1]=>
string(7) "2.2.2.3"
}
www.test.com OK
array(2) {
[0]=>
string(15) "www.example.com"
[1]=>
string(7) "2.2.2.3"
}
www.example.com OK
array(0) {
}
OK
What cause the array(0) to appear?
There's no new line after www.example.com or other element.
Can I remove it or simply don't get it generated?
There's an extra linebreak or other whitespace character after the last domain.
Trim the text file contents first:
$open = trim(file_get_contents($file));
You could also check if the line isn't empty inside the loop.
$file="test.txt";
$open = trim(file_get_contents($file)); // Either this..
$lines = explode(PHP_EOL, $open);
foreach($lines as $line){
if ($line === '') // Or this
continue;
$domain = preg_split('/\s+/', $line,-1,PREG_SPLIT_NO_EMPTY);
echo "<pre>";
var_dump($domain);
echo "$domain[0] OK";
echo "</pre>";
}
Check what contains the last line with:
var_dump($line);
If it contains empty string, just add some check:
if ( empty($line) ) {
continue;
}
I suggest you use the SplFileObject instead:
$path = "test.txt";
$file = new SplFileObject($path);
$file->setFlags(
SplFileObject::DROP_NEW_LINE # new line characters at the end of line
| SplFileObject::SKIP_EMPTY # skip empty lines, e.g. the one at the end
);
foreach ($file as $line)
{
$domain = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
echo "<pre>", var_dump($domain), "$domain[0] OK", "</pre>";
}
It not only has support for your issue build in (see the flags) but also parses the file line by line, so for larger files it would not shift it completely into the memory. See as well the file function.
You're better off using preg_match_all for such an example:
Just names
<?php
$file = 'test.txt';
$open = file_get_contents($file);
preg_match_all('/^\S+/m', $open, $matches);
print_r($matches[0]);
Array
(
[0] => www.google.com
[1] => www.test.com
[2] => www.example.com
)
Names and numbers
<?php
$file = 'test.txt';
$open = file_get_contents($file);
preg_match_all('/^(\S+)\s+(\S+)$/m', $open, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => www.google.com 2.2.2.3
[1] => www.test.com 2.2.2.3
[2] => www.example.com 2.2.2.3
)
[1] => Array
(
[0] => www.google.com
[1] => www.test.com
[2] => www.example.com
)
[2] => Array
(
[0] => 2.2.2.3
[1] => 2.2.2.3
[2] => 2.2.2.3
)
)
$result = array_combine($matches[1], $matches[2]);
print_r($result);
Array
(
[www.google.com] => 2.2.2.3
[www.test.com] => 2.2.2.3
[www.example.com] => 2.2.2.3
)
I have tested your code and found that it's working perfectly...
I got this output by same code
array(2) {
[0]=>
string(14) "www.google.com"
[1]=>
string(7) "2.2.2.3"
}
www.google.com OK
array(2) {
[0]=>
string(12) "www.test.com"
[1]=>
string(7) "2.2.2.3"
}
www.test.com OK
array(2) {
[0]=>
string(15) "www.example.com"
[1]=>
string(7) "2.2.2.3"
}
www.example.com OK
I think there is new line [enter] in your text file please remove it using backspace and it will work fine..

regex match with in { }

I'm having a lot of issues with matching all items that are in brackets.
Here is some code, what I need the matches to do is output something like
Array ( [0] => username [1] => id )
some code to give you an idea
$ur = '/account/{username}/{id}';
if(preg_match('', $str, $matches)){
print_r($matches);
}
How can I accomplish this?
$ur = '/account/{username}/{id}';
preg_match_all('/\{([a-z]+)\}/',$ur,$m);
echo '<pre>';
var_dump($m[1]);
output:
array(2) {
[0]=>
string(8) "username"
[1]=>
string(2) "id"
}

Categories