This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am Having the data like:
$aa ="msg_1";
I want to add +1 at the end of string after doing the explode operation like the following:
$nwMsg =explode("_",$aa);
$inMsg =number_format($nwMsg[1])+1;
$finStr =$nwMsg[0].'_'.$inMsg;
After This i want to form the string again and repeating the same process again but it is increasing up to "10" after that it is not increasing...
You should put the +1 inside the number_format call, not after it.
EDIT: If you just want $nwMsg[1] to be treated as a number, just adding 1 to it will work fine, since + is a numerical operator.
function add_one($string) {
preg_match_all("/[a-zA-Z]+_\d+/", $string, $matches);
$elements = $matches[0];
$last = $elements[count($elements)-1];
$components = explode("_", $last);
$newnum = $components[1] + 1;
return $string . $components[0] . "_" . $newnum;
}
echo add_one("msg_1"); // prints "msg_1msg_2"
echo add_one("msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9"); // prints "msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9msg_10"
$nwMsg =explode("_",$aa);
$inMsg =number_format($nwMsg[1] +1) ;
$finStr =$nwMsg[0].'_'.$inMsg;
$aa= "msg_1";
$new_string= explode("_", $aa);
$new_aa= $new_string[0] ."10";
This is wrong
$inMsg =number_format($nwMsg[1])+1;
This is how it is done
$inMsg =number_format($nwMsg[1]+1);
$nwMsg =explode("_",$aa);
$inMsg =$nwMsg[1] +1 ;
$finStr =$nwMsg[0].'_'.$inMsg;
You will get the result with out using number_format.
One more thing, which can lead to errors and you need to take care - because you want to add two numbers, first make sure that you convert $nwMsg[1] into number (integer or float, it depends):
$nwMsg =explode("_",$aa);
$inMsg =number_format((int)$nwMsg[1]+1);
$finStr =$nwMsg[0].'_'.$inMsg;
How about a different solution:
function add($matches) {
return ++$matches[0];
}
$new = preg_replace_callback("(\d+)", "add", $aa);
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
echo "The smallest multiple of 225 that is only 1's and 0's is: ";
$multiple = (integer) 225;
$factor = (integer) 1;
while (!isDecimalBinary($multiple))
{
$multiple += 225;
$factor += 1;
}
echo $multiple.':'.$factor;
function isDecimalBinary($number)
{
$stringNumber = (string) $number;
$arrayNumber = str_split($stringNumber);
foreach ($arrayNumber as $item)
{
if ($item != '0' || $item != '1')
{
return FALSE;
}
}
return TRUE;
}
I'm tired. It's late. I can't figure where the mistake is here.
Also, I'd thrilled to find a less time consuming method if there's any math tricks to find if a decimal number is all binary digits.
The answer to the specific problem with your code:
explode() doesn't do what you think it does. explode() requires a delimeter parameter, and splits the string out into arrays using that parameter as a separator. If you replace explode() in your code with str_split(), which simply converts the string into an array of characters, the function works correctly.
http://www.php.net/manual/en/function.str-split.php
http://www.php.net/manual/en/function.explode.php
Now, this doesn't actually solve your problem, because you're going to wait a really long time for PHP to chug through and brute-force the correct answer like this. You know how to run a debugger in PHP, right? Debug through your loop and see how obviously inefficient it is. For example, when you hit 2250, you can know without any calculation that the answer cannot possibly be less than 10,000, but you keep checking all the intervening values that cannot possibly start with a 1.
It becomes clear pretty quickly that this is not the correct approach. What if you look at the problem the other way around, and check numbers consisting only of 1's and 0's to see if they're multiples of 255?
Updated solution (http://phpfiddle.org/main/code/dmw-zif)
$i = 1;
$val = $i;
while ($val % 255)
{
$bin = decbin($i++);
$val = (integer) $bin;
}
echo "The smallest multiple of 255 that is only 1's and 0's is: $val, which is equal to 255 *".($val/255);
You are using 225 instead of 255 in your code.
Also you may want to use str_split($stringNumber, 1) instead of explode($stringNumber)
You forget here explode parameter
$arrayNumber = explode($explode_parameter,$stringNumber);
function isDecimalBinary($number)
{
return $number == base_convert(base_convert($number,2,10),10,2);
}
Convert it to base 10 (with precision loss if not base 2) then back to 2. If they're different, it's not all 1s and 0s.
Your function is not calling explode() properly, you can't call it without a delimiter. You could use str_split() instead, but it can be even simpler:
function isDecimalBinary($number)
{
return strspn($number, '01') == strlen($number);
}
Btw, this code requires 64bit integers, otherwise they're turned into doubles and lose precision.
Alternatively, you could use gmp.
$multiple = gmp_init(225);
$factor = 1;
$result = $multiple;
while (!isDecimalBinary(gmp_strval($result))) {
++$factor;
$result = gmp_add($result, $multiple);
}
echo gmp_strval($result).':'.$factor;
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
How do I validate a string against the following rules:
$string = 'int(11)';
Rule: first 4 characters MUST be 'int('
Rule: next must be a number between 1 and 11
Rule: next must be a ')'
Rule: Everything else will fail
Experienced PHP Developer here - Regular Expressions are not my strong point..
Any help or suggestions welcome.
Thanks guys..
if (preg_match('/int\((\d{1,2})\)/', $str, $matches)
&& (int) $matches[1] <= 11 && (int) $matches[1] > 0
) {
// ... do something nice
} else {
echo 'Failed!!!'
}
Or if you want to not use the pReg library (can be faster):
$str = 'int(11)';
$i = substr($str, 4, strpos($str, ')') - 4);
if (substr($str, 0, 4) === 'int('
&& $i <= 11
&& $i > 0
) {
echo 'succes';
} else {
echo 'fail';
}
use this regular expression int\((\d|1[01])\)
int\(( first rule
(\d|1[01]) second rule
\) third rule
This regular expression is even smaller:
int\((\d1?)\)
or without the capturing group (if you don't need to retrieve the numeric value).
int\(\d1?\)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I dont understand why this is giving me an t string syntax error. It looks to me correct! Can somebody please help me out? I am few weeks into my php learning attempt and just trying to make sense of this jumble. I know this is something incredibly stupid but I cannot figure it out!
<?php
// set up some variables
// the toys
$item1 = "X−ray specs";
$item2 = "Watch with built−in poison gas canister";
$item3 = "Exploding chewing gum";
// the price
$item1_cost = 100; $item2_cost = 250; $item3_cost = 32;
// the amount
$item1_qty = 1; $item2_qty = 2; $item3_qty = 15;
// calculate cost for each item
$item1_total = $item1_cost * $item1_qty;
$item2_total = $item2_cost * $item2_qty;
$item3_total = $item3_cost * $item3_qty;
// calculate grand total
$grand_total = $item1_total + $item2_total + $item3_total;
//special secret agent discount − 10%
$discount = 10;
// which reduces total bill amount
$amount = ($grand_total * 10)/100;
// the bottom line
$net_total = $grand_total − $amount;
?>
Somehow you managed to use "–", an n-dash, instead of "-", a minus sign. Did you copy/paste it from a web article? That might have done it. You might also encounter this sort of error if you have “ or ” instead of ", which happens fairly frequently with copying code from web pages.
Change this
$net_total = $grand_total − $amount;
to this
$net_total = $grand_total - $amount;
or just retype the line.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
IGNORE THE QUESTION:
The CSS File I was including pulled in the the other files hence the correlation *facepalm*
We have the following code for picking a CNAME CDN reference per filename. It must return the same URL everytime based on a given filename. We thought this would be sufficiently random:
<?php
function cdn_prefix($fileName) {
$number_of_servers = 4;
$md5 = md5($fileName);
$md5 = substr($md5, 0, 4);
$hash_number = base_convert($md5, 16, 10);
$server_number = ($hash_number % $number_of_servers) + 1;
$server_prefix = '//static' . $server_number . '.' . $_SERVER['SERVER_NAME'];
return $server_prefix . $fileName;
}
?>
However it seems to favour the number 3:
No matter what I do (salt, different bases, random multiplication, etc) the results headerBg through to mainNavPipe (on the screen shot) all have the same number.
Is there a better algorithm?
EDIT:
Here are the results using same algorithm using a SHA1
Everywhere calls the same function - as it returns the whole URL and wouldn't show the static[1-4] domain unless it when through this function.
The array (for testing) is:
FILES = [
'/a/files/image/250.jpg',
'/a/files/image/244.jpg',
'/a/files/image/247.jpg',
'/a/css/global/core.css',
'/a/css/global/print.css',
'/a/img/global/new_logo.gif',
'/a/img/global/book-a-free-survey.gif',
'/a/img/global/make_an_enquiry.gif',
'/a/img/global/purchase-locks-blue.jpg',
'/a/files/image/251.jpg',
'/a/img/global/bg.gif',
'/a/img/global/headerBg.jpg',
'/a/img/global/basketBg.gif',
'/a/img/global/arrow.png',
'/a/img/global/trolley.gif',
'/a/img/global/mainNavBg.gif',
'/a/img/global/mainNavCurrentBg.gif',
'/a/img/global/mainNavPipe.gif',
'/a/img/common/sectionNavBg.jpg',
'/a/img/global/nav_arrow.gif',
'/a/img/global/footerBg.jpg',
'/a/img/global/footerCopyrightBg.jpg',
'/a/img/global/footerLogo.jpg'
]
This was probably a one-time thing or a bug elsewhere.
function cdn_prefix($fileName) {
$number_of_servers = 4;
$md5 = md5($fileName);
$md5 = substr($md5, 0, 4);
$hash_number = base_convert($md5, 16, 10);
$server_number = ($hash_number % $number_of_servers) + 1;
return $server_number;
}
$arr = array(1=>0, 2=>0, 3=>0, 4=>0,);
for ($i = 1; $i < 200000; $i++) {
$arr[cdn_prefix("anrg".$i)]++;
}
print_r($arr);
gives:
Array
(
[1] => 49770
[2] => 50090
[3] => 50026
[4] => 50113
)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
It's probably something simple I am not seeing because I've stared at it too long.
Any ideas? It's throwing on line 119, I've indicated it below
Parse error: syntax error, unexpected T_STRING in /home6/cleanai4/public_html/act.php on line 119
I'm just trying to format a phone number.
if(isset($submit)):
$db = mysql_connect("localhost", "#######", "#######");
mysql_select_db("###########", $db);
$date = date("Y-m-d");
$address = $street . ", " . $city . " " . $zip;
Line 19-> $phonetmp = '('substr($phone, 0, 3)')' . substr($phone, 3, 3) . '-' . substr($phone, 6);
$phone = $tmp;
$sql = "INSERT INTO ########
VALUES(NULL,'$name', '$address', '$email', '$phone', '$info', '$sign', '$date' )";
mysql_query($sql);
print("<h2>We appreciate your support</h2>\n");
print("<b>Now, spread the word</b><hr>\n");
endif;
You're missing the concatenation after the first part of $phonetmp, should be '(' . substr($phone, 0 , 3) . ')'...
Also note: unless you have a variable called $tmp outside of the code segment, you're setting $phone to an undeclared variable. And make sure you sanitize user inputs!
That's not a password I'm seeing in the mysql_connect call is it? ;)