Format Phone Area Code with PHP - php

We have lots of office locations on our website, each with a main phone number - many have been entered with the area code looking like this: (800) 555-5555
This is how I need them to all look, regardless to how it was entered: 800- 555-5555
Here's where I'm at right now
str_replace(array( '(', ')' ), '', $this->data['location_phone']);
While this removes both parenthesis, I really just need to remove the opening one and replace the closing parenthesis with a dash.

Use an array for your replacements.
str_replace(array( '(', ')' ), array('', '-'), $this->data['location_phone']);
You can read more on the str_replace documentation page.

You could do something similar to what you're already doing.. instead of replacing both ( and ) with '', you could just replace ( and then replace ) separately with -.
str_replace(array('('), '', $this->data['location_phone']);
str_replace(array(')'), '-', $this->data['location_phone']);
Or even better, combine into a single line (as indicated in other answers):
str_replace(array( '(', ')' ), array('', '-'), $this->data['location_phone']);

This answer seems to address the issue with preg_match & data reconstruction. But the regex posted in that answer is not that great for the kind of data cleanup described here.
So try this variation of that answer I put together which uses some great regex from a post in the official PHP documentation:
// Set test data.
$test_data = array();
$test_data[] = '1 800 555-5555';
$test_data[] = '1-800-555-5555';
$test_data[] = '800-555-5555';
$test_data[] = '(800) 555-5555';
// Set the regex.
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
// Roll through the test data & process.
foreach ($test_data as $data) {
if (preg_match($regex, $data, $matches)) {
// Reconstruct the number based on the captured data.
echo "New number is: " . $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '<br />';
// Dump the matches to check what is being captured.
echo '<pre>';
print_r($matches);
echo '</pre>';
}
}
And the cleaned results—including the preg_match matches—would be:
New number is: 800-555-5555
Array
(
[0] => 1 800 555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => 1-800-555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => 800-555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => (800) 555-5555
[1] => 800
[2] => 555
[3] => 5555
)

Thanks. I used this for phone number to strip out all the spaces and ( ) and - so the tel://1234567890
href=tel://". str_replace(array( '(', ')',' ','-' ), array('', '','',''), $row["ContactPhone"]).">". $row["ContactPhone"]."

Related

Flatten array of regular expressions

I have an array of regular expressions -$toks:
Array
(
[0] => /(?=\D*\d)/
[1] => /\b(waiting)\b/i
[2] => /^(\w+)/
[3] => /\b(responce)\b/i
[4] => /\b(from)\b/i
[5] => /\|/
[6] => /\b(to)\b/i
)
When I'm trying to flatten it:
$patterns_flattened = implode('|', $toks);
I get a regex:
/(?=\D*\d)/|/\b(waiting)\b/i|/^(\w+)/|/\b(responce)\b/i|/\b(from)\b/i|/\|/|/\b(to)\b/i
When I'm trying to:
if (preg_match('/'. $patterns_flattened .'/', 'I'm waiting for a response from', $matches)) {
print_r($matches);
}
I get an error:
Warning: preg_match(): Unknown modifier '(' in ...index.php on line
Where is my mistake?
Thanks.
You need to remove the opening and closing slashes, like this:
$toks = [
'(?=\D*\d)',
'\b(waiting)\b',
'^(\w+)',
'\b(response)\b',
'\b(from)\b',
'\|',
'\b(to)\b',
];
And then, I think you'll want to use preg_match_all instead of preg_match:
$patterns_flattened = implode('|', $toks);
if (preg_match_all("/$patterns_flattened/i", "I'm waiting for a response from", $matches)) {
print_r($matches[0]);
}
If you get the first element instead of all elements, it'll return the whole matches of each regex:
Array
(
[0] => I
[1] => waiting
[2] => response
[3] => from
)
Try it on 3v41.org
<?php
$data = Array
(
0 => '/(?=\D*\d)/',
1 => '/\b(waiting)\b/i',
2 => '/^(\w+)/',
3 => '/\b(responce)\b/i',
4 => '/\b(from)\b/i',
5 => '/\|/',
6 => '/\b(to)\b/i/'
);
$patterns_flattened = implode('|', $data);
$regex = str_replace("/i",'',$patterns_flattened);
$regex = str_replace('/','',$regex);
if (preg_match_all( '/'.$regex.'/', "I'm waiting for a responce from", $matches)) {
echo '<pre>';
print_r($matches[0]);
}
You have to remove the slashes from your regex and also the i parameter in order to make it work. That was the reason it was breaking.
A really nice tool to actually validate your regex is this :
https://regexr.com/
I always use that when i have to make a bigger than usual regular expression.
The output of the above code is :
Array
(
[0] => I
[1] => waiting
[2] => responce
[3] => from
)
There are a few adjustments to make with your $tok array.
To remove the error, you need to remove the pattern delimiters and pattern modifiers from each array element.
None of the capture grouping is necessary, in fact, it will lead to a higher step count and create unnecessary output array bloat.
Whatever your intention is with (?=\D*\d), it needs a rethink. If there is a number anywhere in your input string, you are potentially going to generate lots of empty elements which surely can't have any benefit for your project. Look at what happens when I put a space then 1 after from in your input string.
Here is my recommendation: (PHP Demo)
$toks = [
'\bwaiting\b',
'^\w+',
'\bresponse\b',
'\bfrom\b',
'\|',
'\bto\b',
];
$pattern = '/' . implode('|', $toks) . '/i';
var_export(preg_match_all($pattern, "I'm waiting for a response from", $out) ? $out[0] : null);
Output:
array (
0 => 'I',
1 => 'waiting',
2 => 'response',
3 => 'from',
)

Most elegant way to clean a string into only comma separated numerals

After instructing clients to input only
number comma number comma number
(no set length, but generally < 10), the results of their input have been, erm, unpredictable.
Given the following example input:
3,6 ,bannana,5,,*,
How could I most simply, and reliably end up with:
3,6,5
So far I am trying a combination:
$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma
But before I keep throwing things at it...is there an elegant way, probably from a regex boffin!
In a purely abstract sense this is what I'd do:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
Example:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>
Here's an example using regex,
$string = '3,6 ,bannana,5,-6,*,';
preg_match_all('#(-?[0-9]+)#',$string,$matches);
print_r($matches);
will output
Array
(
[0] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
[1] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
)
Use $matches[0] and you should be on your way.
If you don't need negative numbers just remove the first bit in the in the regex rule.

How to add double quotes around words-or-phrases-with-spaces-between-words?

Given the following string (Yes, STRING, not Array), I want to add double quotes around the names of countries.
$string = "Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )";
I want the following string:
Array ( [0] => Array ( [nicename] => "Afghanistan" [phonecode] => 93 ) [1] => Array ( [nicename] => "United States" [phonecode] => 1 )
How can I do that?
Note: This String shows only two countries, but the actual data will have more than a hundred counties.
I was thinking of doing something like
$string = preg_replace("/[[:alpha:]]/", "/\"[[:alpha:]]\"/", $string);
But the problem is that for the second argument, (1) how would PHP know what that character class [[:alpha:]] is and (2) The names of countries might contain spaces in addition to alphabetical characters.
You should really be doing this where the array is built but it can be done with a regex...
You need to capture everything after nicename until a [ or ) (e.g. if the nicename is at the end or middle of the "array").
Using something like:
(\[nicename\] => )([^\[)]+)
should accomplish that, then you need to quote the found country name:
$1"$2"
Demo: https://regex101.com/r/7TeUQu/1
this has extra spaces after the country name since whitespace were allowed there. In PHP we'll need to use preg_replace_callback and the trim function to resolve this.
$regex = '/(\[nicename\] => )([^\[)]+)/';
$replace = '$1"$2" ';
$string = 'Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )';
$string = preg_replace_callback($regex, function($match) {
return $match[1] . '"' . trim($match[2]) . '" ';
}, $string);
echo $string;
PHP Demo: https://eval.in/699678
Here you go:
$string = preg_replace('/(\[nicename\] =>) ([a-zA-Z ]+) \[/', '$1 "$2" [', $string);

How to split negative and positive values in string using php?

I have a string variable in php, with look like "0+1.65+0.002-23.9", and I want to split in their individual values.
Ex:
0
1.65
0.002
-23.9
I Try to do with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work I expected.
Can anyone help me out? Thanks a lot in advance.
Like this:
$yourstring = "0+1.65+0.002-23.9";
$regex = '~\+|(?=-)~';
$splits = preg_split($regex, $yourstring);
print_r($splits);
Output (see live php demo):
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
Explanation
Our regex is +|(?=-). We will split on whatever it matches
It matches +, OR |...
the lookahead (?=-) matches a position where the next character is a -, allowing us to keep the -
Then we split!
Option 2 if you decide you also want to keep the + Character
(?=[+-])
This regex is one lookahead that asserts that the next position is either a plus or a minus. For my sense of esthetics it's quite a nice solution to look at. :)
Output (see online demo):
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
Reference
Lookahead and Lookbehind Zero-Length Assertions
Mastering Lookahead and Lookbehind
You could try this
$data = ' 0 1.65 0.002 -23.9';
$t = str_replace( array(' ', ' -'), array(',',',-'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
Which gives you an array containing each field like so:
Array
(
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
)
RE: Your comment: The originals values are in a string variable only separated for a sign possitive or negative
$data = ' 0+1.65+0.002-23.9 ';
$t = str_replace( array('-', '+'), array(',-',',+'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
which gives a similiar answer but with the correct inputs and outputs
Array
(
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
)

php regex split string by [%%%]

Hi I need a preg_split regex that will split a string at substrings in square brackets.
This example input:
$string = 'I have a string containing [substrings] in [brackets].';
should provide this array output:
[0]= 'I have a string containing '
[1]= '[substrings]'
[2]= ' in '
[3]= '[brackets]'
[4]= '.'
After reading your revised question:
This might be what you want:
$string = 'I have a string containing [substrings] in [brackets].';
preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
You should get:
Array
(
[0] => I have a string containing
[1] => [substrings]
[2] => in
[3] => [brackets]
[4] => .
)
Original answer:
preg_split('/%+/i', 'ot limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
You should get:
Array
(
[0] => ot limited to 3
[1] => so it can be
[2] => or
[3] => or
[4] => , etc Tha
)
Or if you want a mimimum of 3 then try:
preg_split('/%%%+/i', 'Not limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
Have a go at http://regex.larsolavtorvik.com/
I think this is what you are looking for:
$array = preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);

Categories