# Check arrary not empty
if (!empty($results)) {
$this->code($results);
// got the mail code from database
// which is PG-000001
// how do i add , like something PG-000001 ++
}
this will return a result from database , my intention is to keep adding up the code that return from my database and the update back to the database.
now it was return PG-000001, how do i make it add up and be like PG-000002 and then update it and next time it will be PG-000002 and up to 000003 and so on.
how do i add up the text PG-000001?
If all of your codes look like this, then your really shouldn’t store them that way. It appears that the PG- at the beginning is just a prefix. If you store the actual value as an integer, you can increment as much as you like.
Anyway, the solution to your question is that you will need to
split the string
increment the second part
zero-pad the second part
combine again
Here is a little test script:
$test='PG-000001';
$pattern='/(.*-)(\d+)/';
preg_match($pattern,$test,$matches);
list(,$prefix,$value)=$matches;
$value=sprintf('%06d',$value+1);
$test="$prefix$value";
print $test;
Translation:
/(.*-)(\d+)/ is the pattern that will split the string into the prefix & numeral
preg_match applies the pattern and returns the result into the array $matches.
$matches has the original string, and then the two matches
list() copies elements of the array into variables. The leading comma skips the first element
sprintf formats the data. In this case, the code 0-pads to 6 digits
the double-quoted string is a simple way of recombining your data.
Related
I have a bunch of variables that I want to string together. They all need to be tidied up by removing spaces and commas, and converting to dashes (I'm constructing a URL).
I have a very basic understanding of PHP, but I feel my code below could be tidier and more efficient. Could you point me to some resources or make some suggestions please?
Here's what I have:
$propNum = $prop->Address->Number;
$propStreet = $prop->Address->Street;
$propTown = $prop->Address->Town;
$propPost = $prop->Address->Postcode;
$propFullAdd = array($propNum, $propStreet, $propTown, $propPost);
$propFullAddImp = implode(" ",$propFullAdd);
$propFullAddTidy = str_replace(str_split(' ,'),'-', strtolower($propFullAddImp));
echo $propFullAddTidy;
From the output of your existing code, it seems like you may want an output that looks something like:
12345-example-street-address-example-town-example-postcode
In this case, you could use this solution:
//loop through all the values of $prop->Address
foreach($prop->Address as $value) {
//for each value, replace commas & space with dash
//store altered value in new array `$final_prop`
$final_prop[] = str_replace([' ', ','], '-', $value);
/*
Removing `str_split(' ,')` and subbing an array makes the loop "cheaper" to do,
Because the loop doesn't have to call the `str_split()` function on every iteration.
*/
}
//implode `$final_prop` array to dash separated string
//also lowercase entire string at once (cheaper than doing it in the loop)
$final_prop = strtolower(implode('-', $final_prop));
echo $final_prop;
if you remove the comments, this solution is only 4 lines (instead of 7), and is completely dynamic. This means if you add more values to $prop->Address, you don't have to change anything in this code.
A different method
I feel like this would usually be handled by using http_build_query(), which converts an array into a proper URL-encoded query string. This means that each value in the array would be passed as it's own variable in the URL query.
First, $propFullAdd is not necessary (in fact, it may be detrimental), $prop->Address already contains the exact same array. Recreating the array like this completely removes the ability to tell which value goes to which key, which could be problematic.
This means that you can simplify your entire code by replacing it with this:
echo http_build_query($prop->Address);
Which outputs something like this:
Number=12345&Street=Example+Street+Address&Town=Example+Town&Postcode=Example+Postcode
I've looked into the similar_text() and levenshtein() functions, but they only seem to return THAT there are similarities and the percentage of those similarities.
What I am trying to do is compare 2 strings to determine WHAT is actually similar between the two.
Basically:
<?php
$string1 = "IMG_1";
$string2 = "IMG_2";
echo CompareTheseStrings($string1,$string2); // returns "IMG_";
If this wonderful function doesn't exist, what would be the best way to accomplish this?
My end game plan is to read through a list of file names and then replace the similar text with something user defined or just remove it all together, but I don't want to replace each files unique identifier.
Reading your 'end goal' I think you're going about this completely the wrong way I think you should really be looking at str_replace
$string1 = "IMG_1";
$string2 = "IMG_2";
// you would create a loop here to insert each string
str_replace("IMG", "NEW_TERM", $string1);
If you want to remove the text altogether then just pass an empty string in as the 2nd parameter
I have a column in my database that stores a string of numbers, separated by commas.
,,133,,,,444,,,,555,,,,6,
Rules:
The first number in the string is always preceded by 2 commas
There are always 4 commas between the middle numbers
The last number only has 1 comma after it
The example above is how I always want the string to look..
What happens is when some of these numbers are removed the updated string looks like this:
,,31,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,998,,,,476,,,,,
Making it look messy in the database and sometimes causing trouble with the extra commas when I try to output each number
I've been manually updating each value to follow the format I want but I'd like to make a script that runs each night and takes each of these strings and updates them with the correct format following the rules I listed above.
What can I use to format the string to follow the rules above?
You could create a php script that loads the values from the database, manipulate the rows, and store the manipulated values back to the database. I don't know what database and table structure you use, but the manipulation part is simple:
// load the string from the database into the $value variable
$numbers= preg_split("/,+/", $value); // split the string
$numbers= array_filter( $numbers); // remove empty array elements
$newvalue = implode(',,,,', $numbers); // join the array elements to a string separated by ,,,,
$newvalue = ',,' . $newvalue . ','; // add ,, at the beginning and , at the end of the new value
// store $newvalue in the database
I have a 15,000 row PHP array. I need to iterate through each row to generate a 15,000 row Javascript array. Each row of the PHP array has a 5% chance of containing one or more HTML special characters like ó that I need to replace with the equivalent javascript hex. There are about 50 HTML special characters I have to look out for and replace, so I'd use str_replace(array_of_HTML_targets, array_of_hex_replacements, haystack). Is it more efficient to:
Go through each line of the PHP array, search for an ampersand, and if one exists do the search and replace (considering this will apply for only 5% of the rows)
Execute the search and replace on the entire array
Concatenate the array into one giant string and execute the search and replace on the giant string
Other idea? Please specify
Btw, reason for 15,000 PHP array is this is a data visualization app.
Since you already need to dump your PHP data into a string (probably JSON), you might as well work on the final string, like so:
$json = json_encode($your_php_array);
$unhtmlref = preg_replace_callback("/&#(x[0-9a-f]+|\d+);/",function($m) {
if( $m[1][0] == "x") $m[1] = substr($m[1],1);
else $m[1] = dechex($m[1]);
return sprintf("\\u%04s",$m[1]);
},$json);
This is safe, because HTML character codes don't have any special meaning in a JSON string.
That said, I have a function in my JavaScript "utility belt" that does something similar:
function unHTMLref(str) {
// take a string and return it, with all HTML character codes parsed
var div = document.createElement('div');
div.innerHTML = str.replace(/</g,"<");
return div.firstChild.nodeValue;
}
So basically you can either parse before, or after. Personally, I'd prefer "after" because it shifts some of the "grunt" work to the browser, allowing the server to do more important things.
I have a text file that has item numbers in it (one per line). When an item is scanned by our barcode scanner it gets placed into this text file IF it exists in the order (which is stored in an array...item numbers only, nothing else).
What's happening is that if I have the two item numbers:
C0DB-9700-W
C0DB-9700-WP
If I scan the item C0DB-9700-W first then I can scan the second item just fine, but if I scan C0DB-9700-WP first, it thinks that I've already scanned C0DB-9700-W because that item is a prefix to the item I've already scanned.
I know that strpos only checks for the first occurrence. I was using the following code:
if (strpos($file_array, $submitted ) !==FALSE) {
I switched to using:
if (preg_match('/'.$submitted.'/', $file_array)) {
I thought that by using preg_match I could overcome the problem, but apparently not. I just want PHP to check the EXACT string I give it against items in the array (which I'm getting from the file) to see if it has already been scanned or not. This isn't that hard in my mind but obviously I'm missing something here. How can I coax PHP into looking for the entire string and not giving up when it finds something that will be good enough (or at least what it thinks is good enough)?
Thanks!
Just use in_array:
if (in_array($submitted, $file_array))
FYI, your regex was missing start/end anchors (and the second argument needs to be a string, not an array):
preg_match('/^'.$submitted.'$/', $subject)
There's nothing inexact about C0DB-9700-WP containing a match for C0DB-9700-W. What you're looking for is a regular expression that ensures the string you want is an entire word by itself:
if (preg_match('/\\b'.$submitted.'\\b/', $file_array)) {
For an array of items $file_array:
if (in_array($submitted, $file_array)) {
// Do something...
}
Although in your examples, it looks like your $file_array is a string, so you'd want to do:
$file_array = explode("\n", $file_array);