PHP finding extent of common sub-string from start - php

I have two strings which starts out the same, but at some point are different. I want to find how many characters the two strings share in common.
It seems like strpos is the opposite of this; it assumes that one string is found completely in another, but not necessarily at the starting offset.
I see a lot of questions which ask about finding common substrings when they aren't at the start, or when there are more than two strings, and this seems to complicate things quite a bit. I have just two strings, and they have a common prefix. IS there a PHP function to get the index at which these two strings differ?

You can try using for loop by comparing character by character. Something like this
$str1 = 'MyStringFirst';
$str2 = 'MyStringSecond';
$match_from_left = '';
$count = 0;
$limit = strlen($str1) > strlen($str2) ? strlen($str2) : strlen($str1);
for($i = 0; $i < $limit; $i++){
if($str1[$i] != $str2[$i]){
break;
}
$count++;
$match_from_left .= $str1[$i];
}
echo 'Count: ' . $count . '<br />';
echo 'Match: ' . $match_from_left . '<br />';

Similar question answered here: Find first character that is different between two strings
You can use the inbuilt PHP function similar_text(), however as pointed out below, this does not get the index, only a count of the number of same characters.

Related

Incrementing a string by one in PHP

I am struggling to find a way to increment a specific pattern required. For each new member, they are given a unique ID such as ABC000001. Each new members ID should increment by one. So the second member's ID would be ABC000002. I am using PHP and MySQL to keep track of each member but I have not been able to come up with a way to properly increment using the string format above.
What is the best way to approach this?
As #axiac mentions this is probably not a good idea but it's pretty easy to manage.
$memberid = 'ABC000001';
list($mem_prefix,$mem_num) = sscanf($memberid,"%[A-Za-z]%[0-9]");
echo $mem_prefix . str_pad($mem_num + 1,6,'0',STR_PAD_LEFT);
Split your current member number into the alpha and numeric parts then put them back together bumping the number when you do it. I use this as a function and pass the previous ID and what I get back is the next ID in the sequence.
You can extract only digits using regex to increment and using str_pad for create a prefix :
$memberid = 'ABC000001';
$num = preg_replace('/\D/', '',$memberid);
echo sprintf('ABC%s', str_pad($num + 1, "6", "0", STR_PAD_LEFT));
Possible answer without regex.
Runs through each character and checks if it is a number or not.
Then uses sprintf() to make sure leading 0s are still there.
$str = "ABC000001";
$number = "";
$prefix = "";
$strArray = str_split($str);
foreach ($strArray as $char) {
if (is_numeric($char)) {
$number .= $char;
} else {
$prefix .= $char;
}
}
$length = strlen($number);
$number = sprintf('%0' . $length . 'd', $number + 1);
echo $prefix . $number;
This works for this instance but would not work if the prefix had numbers in it.
just use the PHP increment operator ++
as long as you've sufficient leading zeros in the pattern, then PHP will correctly increment the numeric component
This code:
<?php
$name = 'ABC0000098';
print ++$name . PHP_EOL;
print ++$name . PHP_EOL;
print ++$name . PHP_EOL;
Outputs:
ABC0000099
ABC0000100
ABC0000101
Read more in the PHP docs:
https://www.php.net/manual/en/language.operators.increment.php
aha - just saw there is already a link to a similar example in the comment posted by "axiac" above

Random generator returning endless duplicates

I am trying to create a random string which will be used as a short reference number. I have spent the last couple of days trying to get this to work but it seems to get to around 32766 records and then it continues with endless duplicates. I need at minimum 200,000 variations.
The code below is a very simple mockup to explain what happens. The code should be syntaxed according to 1a-x1y2z (example) which should give a lot more results than 32k
I have a feeling it may be related to memory but not sure. Any ideas?
<?php
function createReference() {
$num = rand(1, 9);
$alpha = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 1);
$char = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLength = strlen($char);
$rand = '';
for ($i = 0; $i < 6; $i++) {
$rand .= $char[rand(0, $charLength - 1)];
}
return $num . $alpha . "-" . $rand;
}
$codes = [];
for ($i = 1; $i <= 200000; $i++) {
$code = createReference();
while (in_array($code, $codes) == true) {
echo 'Duplicate: ' . $code . '<br />';
$code = createReference();
}
$codes[] = $code;
echo $i . ": " . $code . "<br />";
}
exit;
?>
UPDATE
So I am beginning to wonder if this is not something with our WAMP setup (Bitnami) as our local machine gets to exactly 1024 records before it starts duplicating. By removing 1 character from the string above (instead of 6 in the for loop I make it 5) it gets to exactly 32768 records.
I uploaded the script to our centos server and had no duplicates.
What in our enviroment could cause such a behaviour?
The code looks overly complex to me. Let's assume for the moment you really want to create n unique strings each based on a single random value (rand/mt_rand/something between INT_MIN,INT_MAX).
You can start by decoupling the generation of the random values from the encoding (there seems to be nothing in the code that makes a string dependant on any previous state - excpt for the uniqueness). Comparing integers is quite a bit faster than comparing arbitrary strings.
mt_rand() returns anything between INT_MIN and INT_MAX, using 32bit integers (could be 64bit as well, depends on how php has been compiled) that gives ~232 elements. You want to pick 200k, let's make it 400k, that's ~ a 1/10000 of the value range. It's therefore reasonable to assume everything goes well with the uniqueness...and then check at a later time. and add more values if a collision occured. Again much faster than checking in_array in each iteration of the loop.
Once you have enough values, you can encode/convert them to a format you wish. I don't know whether the <digit><character>-<something> format is mandatory but assume it is not -> base_convert()
<?php
function unqiueRandomValues($n) {
$values = array();
while( count($values) < $n ) {
for($i=count($values);$i<$n; $i++) {
$values[] = mt_rand();
}
$values = array_unique($values);
}
return $values;
}
function createReferences($n) {
return array_map(
function($e) {
return base_convert($e, 10, 36);
},
unqiueRandomValues($n)
);
}
$start = microtime(true);
$references = createReferences(400000);
$end = microtime(true);
echo count($references), ' ', count(array_unique($references)), ' ', $end-$start, ' ', $references[0];
prints e.g. 400000 400000 3.3981630802155 f3plox on my i7-4770. (The $end-$start part is constantly between 3.2 and 3.4)
Using base_convert() there can be strings like li10, which can be quite annoying to decipher if you have to manually type the string.

How to alphabetically order a list of names with special characters in PHP

I've got a list already ordered alphabetically but words with special char (i.e. Cárdena) are outputed at the end of the list... is there a way to order alphabetically even the words with special characters in PHP?
The code outputting the list is:
for($i = $infLimit; $i <= $supLimit; $i++){
$adherido = $lista_adheridos_filtrada[$i];
$numberOfAdheridos = count($lista_adheridos_filtrada);
$nombreAdherido = $adherido->getNombreEntidad();
echo '<li><a target="_blank" title="'.$nombreAdherido.'" href="' . $protocol . '://'.$_SERVER["SERVER_NAME"].'/empresas/'.$adherido->getNombreFicha(). '.htm' . ((isset($_REQUEST["lang"]) && $_REQUEST["lang"] == "en") ? "?lang=en": "") . '">'.$nombreAdherido.'</a></li>';
}
P.S: I tried sort($adherido) but it's not working.
You may be looking for the PHP Collator class:
PHP Collator class documentation
So for example to sort in Spanish, you might do this:
$collator = new Collator('es_ES');
$collator->asort($adherido);

How can i loop this process more effectively

I have written a little script to automate some calculations for me. It is pretty simple.
1*3=3
2*3=6
3*3=9 and so on. When the answer(product) is more than one digit long I want it to add the digits of the answer.
3*4=12 || 1+2=3.
I want it to automatically add the answer if it is more than one digit no matter how many times adding the answer arrives larger than a single digit.
as in when you reach 13*3=39 || 3+9=12 || 1+2=3
Currently my code does not loop, and i cannot figure out how to make it loop here.
http://screencast.com/t/MdpQ9XEz
Also, it is not adding up more than 2 digit answers see 34*3=102. any help here to allow it infinity addition would be great.
As each line is produced the answers get larger, so it should add as many digits there are in the answer.
here is my code:
$i = 1; //Start with one
function count_digit($number) {
return strlen((string) $number);
};
while($i < 500){
$product = $i * 3; //Multiply set
$number_of_digits = count_digit($product); //calls function to count digits of $sum
if($number_of_digits > 1){ //if $sum has more than one digit add the digits together
$addproduct = strval($product);//seperates the digits of $sum
$ii = 0;
while($ii <= $number_of_digits -1){
$io = $ii + 1;
if($io < $number_of_digits){
$one = intval($addproduct[$ii]);
$two = intval($addproduct[$io]);
$sum = $one + $two;
print($i . ' * 3 = ' .$product. ' || ' .$one. ' + ' .$two. ' = ' .$sum. '<br>');
};$ii++;
};
}else{
Print ($i . ' * 3 = ' .$product.'<br>'); //Print Set
};
$i++; //add one
}
For a start, you might replace the $i=1, while ..., and $i++ into one statement: for ($i=0; $i<500; $i++) {.... - see http://nz1.php.net/manual/en/control-structures.for.php for more information about for loops. It comes out to effectively the same code, but keeps the three parts (initialisation, test, increment counter) together; it makes it clear that they are related, and quicker to understand.
Next I would replace conversion of the number to a string, seeing if the length of the string is greater than one, etc.... with:
while ($product>10) {
$out=0;
while ($product) {
$out+=$product%10;
$product=(integer)($product/10);
}
$product=$out;
}
Note that at no time am I treating a number as a string - I avoid that wherever possible.
In case you are not familiar with it, $something+=$somethingelse is the same as $something=$sometime+$somethingelse, just a shorthand. $out is the running total, and each time around the inner loop (while $product), $out is increased by the rightmost digit (the ones column): $out+=$product%10 - see http://nz2.php.net/operators.arithmetic for more info, then $product is divided by 10 and converted to an integer, so 12 becomes 1.2, then 1, dropping the right-most digit.
Each time the inner loop is complete (all the digits of $product are used up, and $product is 0), the result (in $out) is copied to $product, and then you get back to the outer loop (to see if the sum of all these digits is now less than 10).
Also important is exactly where in each loop you print what. The first part, with the multiplication, is immediately in the '500' loop; the '||' happens once for each time '$product' is reduced to '$out'; the adding of the digits happens inside the innermost loop, with '+' either BEFORE each digit except the first, or AFTER each digit except the last. Since 'all except the last' is easier to calculate ($product>=10, watch those edge cases!), I chose that one.
Also note that, since I'm adding the digits from the right to the left, rather than left-to-right, the addition is reversed. I do not know if that will be an issue. Always consider if reversing the order will save you a lot of work. Obviously, if they NEED to be done in a particular order, then that might be a problem.
The result is:
for ($i=0; $i<500; $i++) {
$product = $i * 3; //Multiply set
print ($i . ' * 3 = ' .$product);
while ($product>10) {
print ' || ';
$out=0;
while ($product>0) {
print ($product%10);
if ($product>=10) {
print " + ";
}
$out+=$product%10;
$product=(integer)($product/10);
}
$product=$out;
print(' = ' .$product);
}
print "<br>";
};
I've decided to add this as a separate answer, because it uses a different approach to answer your question: the least amount of changes to fix the problem, rather than rewriting the code in an easy-to-read way.
There are two problems with your code, which require two separate fixes.
Problem 1: Your code does not add 3 digit (or more) numbers correctly.
If you look carefully at your code, you will notice that you are adding pairs of numbers ($one and $two); each time you add a pair of numbers, you print it out. This means that for the number 102, you are adding 1 and 0, printing out the results, then adding 0 and 2 and printing it out. Look carefully at your results, and you will see that 102 appears twice!
One way to fix this is to use $three and $four (4 digits is enough for 500*3). This is not good programming, because if you later need 5 digits, you will need to and $five, and so forth.
The way to program this is to start with a $sum of zero, then go through each digit, and add it to the sum, thusly:
$ii = 0;
$sum = 0;
while($ii <= $number_of_digits - 1){
$one = intval($addproduct[$ii]);
$sum = $sum + $one;
$ii++;
}
print($i . ' * 3 = ' .$product. ' || ' . $sum . '<br>');
};
The inner if disappears, of course, since it relates to $io, which we are no longer using.
Of course, now you lose your ability to print the individual digits as you are adding them up. If you want those in, and since we don't know in advance how many there are, you would have to keep a record of them. A string would be suitable for that. Here is how I would do it:
$ii = 0;
$sum = 0;
$maths = "";
while($ii <= $number_of_digits-1){
$one = intval($addproduct[$ii]);
if ($maths=="") {
$maths=$one;
} else {
$maths=$maths . " + " .$one;
}
$sum = $sum + $one;
$ii++;
}
print($i . ' * 3 = ' .$product. ' || ' . $maths . " = " . $sum . '<br>');
};
Note the lines with $math in them; there's one at the top, setting it to an empty string. Then, once we've decided on what number we're adding, we add this to $maths. The first time round is a special case, since we don't want "+" before our first digit, so we make an exception - if $maths is empty, we set it to $one; later times around the loop, it's not empty, so we add " + " . $one;
Problem 2: if the result of the addition is more than 1 digit long, go around again. And again, as many times as required.
At this point I would suggest a little refactoring: I would break the print statement into several parts. First the multiplication - that can easily be moved to the top, immediately after the actual multiplication. Printing the <br> can go at the end, immediately before the $i++. This also means you no longer need the else clause - it's already done. This only leaves the ' || ' . $maths . " = " . $sum. This is going to have to happen every time you go through the adding.
Now, replace your if($number_of_digits... with a while($number_of_digits...; this means it goes through as many times as is needed, if it's zero or 100. This does mean that you're going to have to update $product at the end of your loop, with $product = $sum; - put this immediately after the print statement. You will also need to update $number_of_digits; copy the line from the top to the end of the loop.
If you've been following along, you should have:
$i = 1; //Start with one
function count_digit($number) {
return strlen((string) $number);
};
while($i < 500){
$product = $i * 3; //Multiply set
print($i . ' * 3 = ' .$product); // Print basic multiplication
$number_of_digits = count_digit($product); //calls function to count digits of $sum
while ($number_of_digits > 1){ //if $sum has more than one digit add the digits together
$addproduct = strval($product);//seperates the digits of $sum
$ii = 0;
$sum = 0;
$maths = "";
while($ii <= $number_of_digits-1){
$one = intval($addproduct[$ii]);
if ($maths=="") {
$maths=$one;
} else {
$maths=$maths . " + " .$one;
}
$sum = $sum + $one;
$ii++;
}
print(" || " . $maths . " = " . $sum ); // print one lot of adding
$product=$sum;
$number_of_digits = count_digit($product); //calls function to count digits of $sum
};
Print ("<br>"); //go to next line
$i++; //add one
}

Learning PHP I need some clarification about concat, combined operators and increment operator

I almost feel stupid asking such basic question, anyway.
I just started learning php on my own by reading some books, before that I used to wander from one online tutorial to another, I should have started from the very basic but I dived head first into if else, foreach, while, arrays etc.
Despite grabbing the concept of those I now realized there are few things that confuse me.
So I was doing this simple exercise, print out the numbers from 1 to 5 using ++ and the *= multiply the power of 2.
$i = 1;
echo $i.'-'.++$i.'-'.++$i.'-'.++$i.'-'.++$i;
Seems all good here, my question is why if I echo $i now it returns 5?
Do I have to reassign the 1 to $i if I want to reuse it later?
I tried to use the same pattern to echo the powers of 2 but all I got was the first and last multiplication.
$p = 1;
echo $p .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-'.$p*= 2 .'-';
Does that mean that I cannot use concatenation if I use combined operators and I would have to echo each line?
Keep in mind I'm restricted to use what is explained in the first two chapters.
Looks like you want a for loop.
$stringVar = "";
for($i=1;$i<6;$i++) {
$stringVar .= "$i -";
}
echo $stringVar;
I'll leave the second one as an exercise for you.
A simple variable (like your $i) stores one digit
so if you do a ++$i, you do the same as $i = $i +1
that means you change the content of your variable
$i = 1;
$i_originalValue = $i;
echo $i.'-'.++$i.'-'.++$i.'-'.++$i.'-'.++$i;
echo $i; //prints 5
echo $i_originalValue; //prints 1

Categories