Check if a String Starts with a Number in PHP [duplicate] - php

This question already has answers here:
Closed 12 years ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Check if a String Ends with a Number in PHP
I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function startsWithNumber($string) {
$startsWithNumber = false;
// Logic
return $startsWithNumber;
}

You can use substr and ctype_digit:
function startsWithNumber($string) {
return strlen($string) > 0 && ctype_digit(substr($string, 0, 1));
}
The additional strlen is just required as ctype_digit returns true for an empty string before PHP 5.1.
Or, if you rather want to use a regular expression:
function startsWithNumber($str) {
return preg_match('/^\d/', $str) === 1;
}

Something like to this may work to you:
function str2int($string) {
$length = strlen($string);
for ($i = 0, $int = ''; $i < $length; $i++) {
if (is_numeric($string[$i]))
$int .= $string[$i];
else break;
}
return (int) $int;
}

Related

PHP sum last 6 digit from substring [duplicate]

This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 8 months ago.
I'm trying to adding all numbers from last 6 digit from substr(). Let say the number is 19283774616, I'm trying to have result from this: 7+7+4+6+1+6 = ?. Here is my current code
public function accountHash($accountNumber)
{
$result = 0;
$accountNumber = substr($accountNumber, -6);
for($i=0; $i<=strlen($accountNumber); $i++) {
$result += substr($accountNumber, $i, 1); // A non-numeric value encountered here
}
echo $result;
}
From the function above, "A non-numeric value encountered" error occurred. Need suggestion on how to do this. Thank you
You attempt to get more characters than string contains. Replace "<=" with "<" in your condition expression, i.e. change:
for($i=0; $i<=strlen($accountNumber); $i++) {
to
for($i=0; $i<strlen($accountNumber); $i++) {
You need to use < instead of <= in your for loop.
And you can do it a more simple way,
$result = 0;
for($i = 0; $i < 6; $i++){
$result += $string[-$i];
}
An alternative method without loops (or error checking, for what it's worth):
function accountHash($accountNumber)
{
return array_sum(
preg_split('//u', mb_substr($accountNumber, -6), null, PREG_SPLIT_NO_EMPTY)
);
}
Demo

Split a number by 13 digits using php [duplicate]

This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}

PHP 2 chars decrement (AB -> AA) [duplicate]

This question already has answers here:
Increment letters like number by certain value in php
(2 answers)
Closed 4 years ago.
I am implementing some export functions using PHPExcel.
Since PHP can increment alphabet automatically it had been working fine but I have an issue when trying to decrement it.
I can decrement a single character like this $decremented = chr(ord($someChar) - 1);, but it does not work on 2 characters (such as 'AA','BB', .. etc.)
Is there any way that I can decrement two characters? Like 'ZZ' -> 'ZX', 'AA'->'Z'
Any help or thoughts would be really appreciated!
Here's a decrement function that will work for you:
function decrement($str) {
$index = strlen($str)-1;
$ord = ord($str[$index]);
if ($ord > 65) {
// The final character is still greater than A, decrement
return substr($str, 0, $index) . chr($ord-1);
}
if ($index > 0) {
// Strip the final 2 characters and append a Z
return substr($str, 0, $index-1) . 'Z';
}
// Can't be decremented
return false;
}
https://3v4l.org/WaaKY
Somebody wrote a function for this here.
function decrementLetter($char) {
$len = strlen($char);
// last character is A or a
if(ord($char[$len - 1]) === 65 || ord($char[$len - 1]) === 97){
if($len === 1){ // one character left
return null;
}
else{ // 'ABA'--; => 'AAZ'; recursive call
$char = decrementLetter(substr($char, 0, -1)).'Z';
}
}
else{
$char[$len - 1] = chr(ord($char[$len - 1]) - 1);
}
return $char;
}

Random string generator PHP [duplicate]

This question already has answers here:
PHP random string generator
(68 answers)
Closed 7 years ago.
I'm trying to create a random string with numbers and letters and I found this function and thought it would be good, but I don't know if it is the correct way to create a true random string or if there is an easier way to do this? Below is what I have:
function randomGen() {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($chars);
$random;
for ($i = 0; $i < 8; $i++) {
$random = $chars[rand(0, $length - 1)];
}
return $random;
}
You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done in one line of code!

How write all possible words in php? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generate all combinations of arbitrary alphabet up to arbitrary length
I'm trying to make write all possible words of 10 letters(zzzzzzzzzz) in php. How can I do that? it will look like that : http://i.imgur.com/sgUnL.png
I tried some ways to it but they are only making 10 letters randomly not increasing from 1 letter. By the way execution time and how it's big is not problem. i just need to algorithm for it, if somebody show it with code it'll be more helpful of course..
function words($length, $prefix='') {
if ($length == 0) return;
foreach(range('a', 'z') as $letter) {
echo $prefix . $letter, "\n";
words($length-1, $prefix . $letter);
}
}
Usage:
words(10);
Try it here: http://codepad.org/zdTGLtjY (with words up to 3 letters)
Version 1:
for($s = 'a'; $s <= 'zzzzzzzzzz'; print $s++.PHP_EOL);
as noted by Paul in comments below, this will only go to zzzzzzzzyz. A bit slower (if anyone cares) but correct version would be:
//modified to include arnaud576875's method of checking exit condition
for($s = 'a'; !isset($s[10]); print $s++.PHP_EOL);
<?php
function makeWord($length, $prefix='')
{
if ($length <= 0)
{
echo $prefix . "\n";
return;
}
foreach(range('a', 'z') as $letter)
{
makeWord($length - 1, $prefix . $letter);
}
}
// Use the function to write the words.
$minSize = 1;
$maxSize = 3;
for ($i = $minSize; $i <= $maxSize; $i++)
{
makeWord($i);
}
?>

Categories