PHP regex vs explode() for phone number - php

I have been messing around with some regular expressions, and I ran into a small hiccup with a more complicated version of my phone number formatting.
Here's what I am working with:
$number1 = '+1 (123) 1234567';
$number1 = '+966 (1) 1234567 x555';
These strings are actually being output from the MySQL query I created, and I love it.
However, I'm making a simple php function to auto-format the subscribers number from 1234567 to 123-4567.
I'm not too concerned about any number that doesn't start with +1. So I'm formatting US and Canadian numbers.
Here's what I attempted, if there was only 7 digits, and if the string starts with +1
<?php
function format_phonenumbers($phone){
if(empty($phone)){ return ''; }
$exploded = explode(' ',$phone);
$countrycode = $exploded[0];
$areacode = $exploded[1];
$number = $exploded[2];
$ext = (!empty($exploded[3])?$exploded[3]:'');
if($countrycode=='+1'){
$strphone = strlen($number);
if ($strphone == 7) { // auto-format US PHones
$prefix = substr($number,0,3);
$suffix = substr($number,-4);
}
$phone = $countrycode.' '.$areacode.' '.$prefix.'-'.$suffix.' '.$ext;
}
return $phone;
}
echo format_phonenumbers('+1 (714) 1234567'); // US domestic
echo '<br>';
echo format_phonenumbers('+966 (1) 1234567 x555'); // international
?>
This formats what I need, but I'm curious if anyone believes I can do this in a better way. Like using a regex checker, that finds anything after the parenthesis, but before an extension, rather than using the explode() function.

Something like:
function format_phonenumbers($phone)
{
return preg_replace_callback(
'/([)]\s*)(\d{3,3}(\d+)/',
function ($match) {
return $match[1] . $match[2] . '-' . $match[3];
},
$phone
);
}
This should work, but requires PHP 5.3.0 or higher (if not you'll have to use create_function). Its arguable if it is any better however.

Related

Get range letter and number with php

how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?
This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!

How can I divide streetnr and street out of one String?

I want to divide an String into var street and streetnr. How can I do this with php?
The data look like:
Bakerstreet 5
Wild Street 5 a
Best Street 5a
Simplestreet
I have Streets without numbers and Streets with letters ... How can I do this?
So the street should always be like
var street = Bakerstreet, Wild Street, Best Street, Simplestreet
var streetnr should always be = 5, 5 a, 5a
My idea was to explode the string after every blank " " ... Then I reverse the array and look if the first element is just a letter. If it is, I put it into streetnr. Then I check the next element. If there are just numbers, I put it into streetnr ... and so on
I've used this as an excercise for my PHP-Training. And while I'm a huge fan of regex, I wanted to do it without em and came up with the following:
<?php
$addr = array("Bakerstreet 5",
"Wild Street 5 a",
"Best Street 5a",
"Simplestreet",
"Won't Work 47a Suite 18b",
"1st Street 10b ",
"Route 66 12a "
);
echo "<h1>Address-Parsing</h1><ol>";
foreach ($addr as $ad)
{
$no=""; // Number
$st=""; // Street
$GotNo = false;
$r = strrev(trim($ad));
echo "<li>ad=$ad";
do {
while ($r{0}=="0") {// special handling for leading "0"s (in reverted string) which are ignored by sscanf...
if (!$GotNo) $no = "0" . $no;
else $st = "0" . $st;
$r = substr($r,1);
}
$d = sscanf($r,"%d"); // get number
$s = sscanf($r,"%c"); // get string
if (is_null($d[0]) && !$GotNo) {
// no matching number and have not matched no yet - so this must be string following the nr
$no = strrev($s[0]) . $no;
$r = substr($r,strlen($s[0])); // remove match
} elseif (!$GotNo) {
$no = strrev($d[0]) . $no;
$GotNo = true;
$r = substr($r,strlen($d[0])); // remove match
} else {// we already have a number, so any text must be streetname
$st = strrev($r) . $st;
$r="";
}
if ($r !== trim($r)) {$st = " " . $st; $r = trim($r);}
} while (0<strlen($r));
$st = trim( $st);
if (empty($st)) {// might happen when no number was found...
$st=$no;
$no="";
}
echo "|st=$st|no=$no|</li>";
}
echo "</ol>";
?>
Use a regular Expression
preg_match('~^\s*(.*)\s+([0-9]+\s*[a-zA-Z]{0,1})\s*$~', $street, $match);
preg_match returns true if the street is in the right format and $match is an array containing [1]=street name, [2]=streetnr.
You could match using the following regular expression:
preg_match('/^(.+?)(?:\s+(\d.*))?$/', $street, $matches);
$street = $matches[1];
if (count($matches) == 3)
$streetnr = $matches[2];

php calculate formula in string [duplicate]

This question already has an answer here:
How to evaluate formula passed as string in PHP?
(1 answer)
Closed 9 years ago.
So I have formula as string
$comm = "(a x 5% - 2%)";
I want it to be $comm = $a * 5/100 * (1-2/100);
How can I do this in php?
Take a look at
http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html
Which can evaluate Math Code
// instantiate a new EvalMath
$m = new EvalMath;
$m->suppress_errors = true;
// set the value of x
$m->evaluate('x = 3');
var_dump($m->evaluate('y = (x > 5)'));
Found at:
Process mathematical equations in php
To do this the right way, reliably and safely, from scratch, you will need to perform:
Lexical analysis, this involves pattern matching the input with tokens:
(a x 5% - 2%)
would become something like the following chain of tokens:
openparen variable multiply integer percent minus integer percent closeparen
Syntax analysis, this involves taking those tokens and defining the relationships between them, something like this, matching up the patterns of tokens:
statement = operand operator statement
Then you will need to parse the resulting syntax tree so that you can run it and produce the answer.
It won't ever look as simple as $comm = $a * 5/100 - 2/100; but it will result in the same conclusion.
Someone somewhere has already likely had a go at this problem, here's two I found after a brief Google search:
PHP Maths Expression Parser,
And another.
These SO questions are similar as well Smart design of a math parser?, Process mathematical equations in php
It just trying, but maybe good start.
$somm = 0;
$a = 30;
$str = "(a x 5% - 2%)";
$pt1 = "/x/i";
$str = preg_replace($pt1, "*", $str);
$pt2 = "/([a-z])+/i";
$str = preg_replace($pt2, "\$$0", $str);
$pt3 = "/([0-9])+%/";
$str = preg_replace($pt3, "($0/100)", $str);
$pt4 = "/%/";
$str = preg_replace($pt4, "", $str);
$e = "\$comm = $str;";
eval($e);
echo $e . "<br>";
echo $comm;
Solved!!
<?php
function evalmath($equation)
{
$result = 0;
// sanitize imput
$equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
// convert alphabet to $variabel
$equation = preg_replace("/([a-z])+/i", "\$$0", $equation);
// convert percentages to decimal
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
$equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
/*if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
return $result;*/
return $equation;
}
$total = 18000;
$equation = evalmath('total-(230000*5%-2%+3000*2*1)');
if ( $equation != "" ){
$result = #eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;
?>

Can I use the $string number_format line to superscript my decimals?

I would like to make the decimals in the following string display as superscript:
$string .= number_format(round($value, (int)$decimal_place), (int)$decimal_place, $decimal_point, $thousand_point);
I'm not very smart but I have been trying since yesterday using different methods I've found searching stack overflow. Stuff like ."<sup> or just "<sup>" and also .'<sup>' and so many other combinations, but nothing works. I either get an error or the price disappears due to the error I introduce into the code because as I said I'm not the sharpest tool in the shed.
Please check out the code I have below, this will format your string, and then use regular expressions to superscript the decimal
<?
function superscript_value($value, $prefix = '$') {
$decimal_place = 2;
$decimal_point = '.';
$thousand_point = ',';
if(round($value, 0) == $value)
return $prefix . $value;
else
return $prefix . preg_replace("/\.(\d*)/", "<sup>.$1</sup>", number_format($value, (int)$decimal_place, $decimal_point, $thousand_point));
}
echo superscript_value(123456.789, '$') . "\n";
// $123,456<sup>.79</sup>
echo superscript_value(10.00, '$') . "\n";
// $10
$123,456.79
$10
You should use HTML formatting for that:
$i = 42;
$string .= "<sup>".$i."</sup>";
It will produce something like 42.

PHP Regex to Find Any Number at the Beginning of String

I'm using PHP, and am hoping to be able to create a regex that finds and returns the street number portion of an address.
Example:
1234- South Blvd. Washington D.C., APT #306, ZIP45234
In the above example, only 1234 would be returned.
Seems like this should be incredibly simple, but I've yet to be successful. Any help would be greatly appreciated.
Try this:
$str = "1234- South Blvd. Washington D.C., APT #306, ZIP4523";
preg_match("~^(\d+)~", $str, $m);
var_dump($m[1]);
OUTPUT:
string(4) "1234"
I know you requested regex but it may be more efficient to do this without (I haven't done benchmarks yet). Here is a function that you might find useful:
function removeStartInt(&$str)
{
$num = '';
$strLen = strlen($str);
for ($i = 0; $i < $strLen; $i++)
{
if (ctype_digit($str[$i]))
$num .= $str[$i];
else
break;
}
if ($num === '')
return null;
$str = substr($str, strlen($num));
return intval($num);
}
It also removes the number from the string. If you do not want that, simply change (&$str) to ($str) and remove the line: $str = substr($str, strlen($num));.

Categories