Replace Leading zero with '+' in PHP - php

I want to replace the leading zero in a phone number with '+' and country code.
If the phone number starts with zero (ex: 07512345678) then I want to remove the leading zero and replace with '+' and country code else (ex: 7512345678)just add '+' and country code.
What would the way to do that in PHP?

Use preg_replace()
$newNumber = preg_replace('/^0?/', '+'.$countryCode, $phoneNumber);
The first parameter is the regular expression, which is looking for that leading zero of yours. The second is what you want to replace it with (the plus sign concatenated with the country code.). Finally, $phoneNumber is the original phone number.
The replaced value is assigned to the variable $newNumber. Feel free to change the variables to fit your code.

Use substr_replace(), no need for regex or if blocks.
$number = '07512345678';
$country_code = '44';
$new_number = substr_replace($number, '+'.$country_code, 0, ($number[0] == '0'));

You could use preg_replace:
$newNumber = preg_replace("/^0/", "+", 07512345678)
This will replace the first character of each number if and only if it is zero. The regular expression used is: /^0/. The ^ tells it to look at the first character, and then only match a 0 thereafter. This 0 will be replaced with the second argument, the "+". The last argument is the source string.
Reference
Take a look at preg_replace here
Basic syntax for beginning REGEX here

You can use string manipulation:
$x = '012345678';
if ($x[0]=='0') $x[0] = ''; // delete leading zero
$x = '+1'.$x;

preg_match() is less effective I suspect, due to the complexity of the whole system.
<?php
$countryCode = "XX";
$phone = array("0123455", "7837373");
foreach( $phone AS $number ) {
if( $number[0] == '0' ) {
$number = "+{$countryCode}" . substr($number,1);
}
echo "{$number}\n";
}
PS: this is elementary. You should really got through some tutorials.

Related

PHP - Check for leading 0's in 2 comma-delimited integers

I have a user-input string with 2 comma-delimited integers.
Example (OK):
3,5
I want to reject any user input that contains leading 0's for either number.
Examples (Bad):
03,5
00005,3
05,003
Now what I could do is separate the two numbers into 2 separate string's and use ltrim on each one, then see if they have changed from before ltrim was executed:
$string = "03,5";
$string_arr = explode(",",$string);
$string_orig1 = $string_arr[0];
$string_orig2 = $string_arr[1];
$string_mod1 = ltrim($string_orig1, '0');
$string_mod2 = ltrim($string_orig2, '0');
if (($string_mod1 !== $string_orig1) || ($string_mod2 !== $string_orig2)){
// One of them had leading zeros!
}
..but this seems unnecessarily verbose. Is there a cleaner way to do this? Perhaps with preg_match?
You could shorten the code and check if the first character of each part is a zero:
$string = "03,5";
$string_arr = explode(",",$string);
if ($string_arr[0][0] === "0" || $string_arr[1][0] === "0") {
echo "not valid";
} else {
echo "valid";
}
Here is one approach using preg_match. We can try matching for the pattern:
\b0\d+
The \b would match either the start of the string, or a preceding comma separator.
If we find such a match, it means that we found one or more numbers in the CSV list (or a single number, if only one number present) which had a leading zero.
$input = "00005,3";
if (preg_match("/\b0\d+/", $input)) {
echo "no match";
}
You can do a simple check that if the first character is 0 (using [0]) or that ,0 exists in the string
if ( $string[0] == "0" || strpos($string, ",0") !== false ) {
// One of them had leading zeros!
}
All the current answers fail if any of the values are simply 0.
You can just convert to integer and back and compare the result.
$arr = explode(',', $input);
foreach($arr as $item) {
if( (str)intval($item) !== $item ) {
oh_noes();
}
}
However I am more curious as to why this check matters at all.
One way would be with /^([1-9]+),(\d+)/; a regex that checks the string starts with one or more non-zero digits, followed by a comma, then one or more digits.
preg_match('/^([1-9]+),(\d+)/', $input_line, $output_array);
This separates the digits into two groups and explicitly avoids leading zeros.
This can be seen on Regex101 here and PHPLiveRegex here.

PHP search in a variable text and save it

I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.
You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for
Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...
Hello I would use a preg_match regex using this regular expression : \d{4}
here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}

Big numbers regex

$value = preg_replace("/[^0-9]+/", '', $value);
How could I edit this regex to get rid of everything after the decimal point? There may or may not be a decimal point.
Currently "100.1" becomes 1001 but it should be 100.
Complete function:
function intfix($value)
{
$value = preg_replace("/[^0-9]+/", '', $value);
$value = trim($value);
return $value + 0;
}
It is used to format user input for numbers as well as servers output to format numbers for the DB. The functions deals with very large numbers, so I can't use intval or similar. Any extra comments to improve this function are welcome.
You could just change the regex to /[^0-9].*/s.
.* matches zero or more characters, so the first character that is not a digit, and the digits that immediately follow, would be deleted.
You need to have a pattern that starts the search with a decimal place. At the moment you're only deleting the . not the numbers after it... So you could do '/\.[\d]+/'
$text = "1201.21 12 .12 12.21";
$text = preg_replace('/\.[\d]+/', '' ,$text);
The above code would result in $text = "1201 12 12"
Why not $value = round($value, 0);? This can handle large values and is meant to get rid of the following decimals mathematically (I'd rather work with numbers as numbers not as strings). You can pass PHP_ROUND_HALF_DOWN as a third parameter if you want to just get rid of the decimals 10.7 -> 10. Or floor($value); could work too.

Validating special form of IP address

I have encountered a strange IP which has redundant zero values among the octets. Is there anyway to properly validate this as an IP or use regular expression to remove those redundant zeroes?
example is of follows:
218.064.215.239 (take note of the extra zero at the second octet "064").
I do have one working IP validation function but it will not validiate this Ip properly due to the nature of the regular expression unable to accept that extra zero. Following is the code in PHP:
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" .
"(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
thanks for any help in advance peeps! :D
This will correct them:
$ip = "123.456.007.89";
$octets = explode(".", $ip);
$corrected = array();
foreach ($octets as $octet) {
array_push($corrected, (int)$octet);
}
echo implode(".", $corrected);
You have to accept the zero like this:
^(0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(0?[0-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$
Play with this regular expression on rubular.com.
The 0? I added matches zero or one occurence of 0. So 0?[1-9][0-9] for example matches both 010 and 10 for example.
Change the bare |1 occurrences to |[01]. Are you sure this is not supposed to be interpreted as an octal number, though? Some resolvers do that.
Use ip2long().
You should figure out where those extra zeroes are coming from. Those leading zeroes can't be just dropped. On most platforms they mean that the octet is in octal form instead of decimal. That is: 064 octal equals 52 decimal.
Did you have a go yourself? It's really quite simple.
|1[0-9][0-9]| matches 100-199, as you are now wanting to match 000-199 (as above that it is 200-155) you just need to make a set for the 1 to be 1 or 0.
function valid_ip($ip) {
return preg_match("/^([1-9]|[1-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])".
"(\.([0-9]|[1-9][0-9]|[01][0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
And that can be refactored down (allowing leading zeroes) to:
function valid_ip($ip) {
return preg_match("/^([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])".
"(\.([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){3}$/", $ip);
}
Or to strip these unneeded zeros:
function strip_ip($ip) {
return preg_replace( '/0+([^0])(\.|$)/' , '$1$2' , $ip );
}

check for number anywhere in a string

$vari = "testing 245";
$numb = 0..9;
$numb_pos = strpos($vari,$numb);
echo substr($vari,0,$numb_pos);
The $numb is numbers from 0 to 9
Where am I wrong here, all I need to echo is testing
You want to cut out the numbers from a string?
$string = preg_replace('/(\d+)/', '', 'String with 1234 numbers');
Use a regular expression to strip numeric characters from your string.
or, use a regular expression to find the first instance of one either way...
Your code won't work as-is, as it'll fail if the number if the first character in the string. (You need to check $numb_pos !== false prior to the substr.)
Irrespective, if you just want to check for the existance of a number in a string, something like the following would probably be more efficient.
$digitMatched = preg_match('/\\d/im', $vari);

Categories