Replace first character of sting in PHP with rules - php

I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?

Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];

I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk

Related

Find and Replace Multi-Row Phrases/text Within PHP Arrays without damaging the array

Lets say I have an array:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Sundays',
[4] => 'which are also pretty good days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Keeping the structure of this array intact, I want to be able to replace phrases within it, even if they spill over to the next or previous string. Also I don't want punctuation or case to impact it.
Examples:
String to Find:
"Sundays which are also pretty good"
Replace with:
"Mondays which are also pretty great"
After replace:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Mondays',
[4] => 'which are also pretty great days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Curious if there is an ideal way of doing this. My original thought was, I would turn the array into a string, strip out punctuation and spaces, count the characters and replace the phrase based on the character count. But, it is getting rather complex, but it is a complex problem
This is a job for regular expressions.
The method I used was to implode the array with some glue (i.e. '&'). Then I generated a regular expression by inserting a zero-or-one check for '&' in between each character in the find string.
I used the regular expression to replace occurrences of the string we were looking for with the replacement string. Then I exploded the string back into an array using the same delimiter as above ('&')
$myarray = [
0 => 'Johnny likes to go to school',
1 => 'but he only likes to go on Saturday',
2 => 'because Saturdays are the best days',
3 => 'unless you of course include Mondays',
4 => 'which are also pretty great days too.',
5 => 'Sometimes Johnny likes picking Strawberrys',
6 => 'with his mother in the fields',
7 => 'but sometimes he likes picking blueberries'
];
// preg_quote this because we're looking for the string, not for a pattern it might contain
$findstring = preg_quote("Sundays which are also pretty good");
// htmlentities this in case it contains a string of characters which happen to be an html entity
$replacestring = htmlentities("Mondays which are also pretty great");
// Combine array into one string
// We use htmlentitles to escape the ampersand, so we can use it as a sentence delimeter
$mystring = implode("&", array_map('htmlentities', $myarray));
// Turns $findString into:
// S\&?u\&?n\&?d\&?a\&?y\&?s\&? \&?w\&?h\&?i\&?c\&?h\&? \&?a\&?r\&?e\&?
// \&?a\&?l\&?s\&?o\&? \&?p\&?r\&?e\&?t\&?t\&?y\&? \&?g\&?o\&?o\&?d
$regexstring = implode("\&?", str_split($findstring));
// Johnny likes to go to school&but he only likes to go on Saturday&because Saturdays are the
// best days&unless you of course include Mondays&which are also pretty great days
// too.&Sometimes Johnny likes picking Strawberrys&with his mother in the fields&but sometimes
// he likes picking blueberries
$finalstring = preg_replace("/$regexstring/", $replacestring, $mystring);
// Break string back up into array, and return any html entities which might have existed
// at the beginning.
$replacedarray = array_map('html_entity_decode', explode("&", $finalstring));
var_dump($replacedarray);

How can I split a string into LETTERS and FLOAT/INTEGER numbers

I've been trying for the couple of days to split a string into letters and numbers. I've found various solutions but they do not work up to my expectations (some of them only separate letters from digits (not integers or float numbers/per say negative numbers).
Here's an example:
$input = '-4D-3A'; // edit: the TEXT part can have multiple chars, i.e. -4AB-3A-5SD
$result = preg_split('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', $input);
print_r($result);
Result:
Array ( [0] => -4 [1] => D-3 [2] => A )
And I need it to be [0] => -4 [1] => D [2] => -3 [3] => A
I've tried doing several changes but no result so far, could you please help me if possible?
Thank you.
try this:
$input = '-4D-3A';
$result = preg_split('/(-?[0-9]+\.?[0-9]*)/i', $input, 0, PREG_SPLIT_DELIM_CAPTURE);
$result=array_filter($result);
print_r($result);
It will split by numbers BUT also capture the delimiter (number)
giving : Array ( [1] => -4 [4] => D [5] => -3 [8] => A )
I've patterened number as:
1. has optional negative sign (you may want to do + too)
2. followed by one or more digits
3. followed by an optional decimal point
4. followed by zero or more digits
Can anyone point out the solution to "-0." being valid number?
How about this regex? ([-]{,1}\d+|[a-zA-Z]+)
I tested it out on http://www.rubular.com/ seems to work as you want.

How to stop PHP from rounding my barcode numbers

I have some bar code numbers in an array. PHP seems to be rounding the barcodes which start with leading zeros. How do I stop this happening and keep the numbers as they were? Code I am using is below:
$array = array(5032227448124,5060028999989,5010121096504,5060028999996,5016254104864,5016402052788,8422248036986,0000003798720,0000003735503,0000003798713);
echo '<pre>';
print_r($array);
echo '</pre>';
This echos the following, as you can see the last four bar codes which feature leading zeros have been changed and had their leading zeros removed. These numbers are always 13 digits long and are padded with zeros.
Array
(
[0] => 5032227448124
[1] => 5060028999989
[2] => 5010121096504
[3] => 5060028999996
[4] => 5016254104864
[5] => 5016402052788
[6] => 8422248036986
[7] => 31
[8] => 1030979
[9] => 31
[10] => 1031004
)
You need to quote them as strings if they arent a number (integer, float, exponent).
The obvious, easy, and also likely wrong answer is to make them strings.
The better answer is to use printf()/sprintf() to pad with zeroes:
printf('%013d', 12345); // output: 0000000012345
MySQL also has a handy LPAD() function:
SELECT LPAD(12345, 13, 0) // output 0000000012345
Here's an easy way to convert your values to padded strings:
$array = array_map(function ($e){return str_pad($e, 13, "0", STR_PAD_LEFT);}, $array);
In the end I just needed to put double quotes around each barcode number e.g.
$array = array("5032227448124","5060028999989","5010121096504","5060028999996","5016254104864","5016402052788","8422248036986","0000003798720","0000003735503","0000003798713");

php split integer into smaller parts

i'm working on a project that will need to have everything shown with barcodes, so I've generated 7 numbers for EAN8 algorithm and now have to get these 7 numbers seperately, right now i'm using for the generation
$codeint = mt_rand(1000000, 9999999);
and I need to get this 7 numbers each seperately so I can calculate the checksum for EAN8, how can i split this integer to 7 parts, for example
12345678 to
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4
arr[4]=5
arr[5]=6
arr[6]=7
any help would be appreciated..
also I think that I'm becoming crazy :D because I already tried most of the solutions you gave me here before and something is not working like it should work, for example:
$codeint = mt_rand(1000000, 9999999);
echo $codeint."c</br>";
echo $codeint[1];
echo $codeint[2];
echo $codeint[3];
gives me :
9082573c
empty row
empty row
empty row
solved! $codeint = (string)(mt_rand(1000000, 9999999));
Try to use str_split() function:
$var = 1234567;
print_r(str_split($var));
Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
There are two ways to do this, one of which is reasonably unique to PHP:
1) In PHP, you can treat an integer value as a string and then index into the individual digits:
$digits = "$codeint";
// access a digit using intval($digits[3])
2) However, the much more elegant way is to use actual integer division and a little knowledge about mathematical identities of digits, namely in a number 123, each place value is composed of ascending powers of 10, i.e.: 1 * 10^2 + 2 * 10^1 + 3 * 10^0.
Consequently, dividing by powers of 10 will permit you to access each digit in turn.
it's basic math you can divide them in loop by 10
12345678 is 8*10^1 + 7*10^2 + 6*10^3...
the other option is cast it to char array and then just get it as char
Edit
After #HamZa DzCyberDeV suggestion
$string = '12345678';
echo "<pre>"; print_r (str_split($string));
But in mind it comes like below but your suggestion is better one.
If you're getting string from your function then you can use below one
$string = '12345678';
$arr = explode(",", chunk_split($string, 1, ','));
$len = count($arr);
unset($arr[$len-1]);
echo "<pre>";
print_r($arr);
and output is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
okay what you can do is
Type cast to string with prefill 0
this is how it works
$sinteger = (string)$integer;
$arrsize = 0 ;
for (i=strlen($sinteger), i == 0 ; i--)
{
arr[$arrsize]=$sinteger[i];
$arrsize++;
}
And then what is left you can prefill with zip.
I am sure you can manage the order reverse or previous. but this is simple approach.

regex to find year/month substring

Can someone help me with a regular expression to get the year and month from a text string?
Here is an example text string:
http://www.domain.com/files/images/2012/02/filename.jpg
I'd like the regex to return 2012/02.
This regex pattern would match what you need:
(?<=\/)\d{4}\/\d{2}(?=\/)
Depending on your situation and how much your strings vary - you might be able to dodge a bullet by simply using PHP's handy explode() function.
A simple demonstration - Dim the lights please...
$str = 'http://www.domain.com/files/images/2012/02/filename.jpg';
print_r( explode("/",$str) );
Returns :
Array
(
[0] => http:
[1] =>
[2] => www.domain.com
[3] => files
[4] => images
[5] => 2012 // Jack
[6] => 02 // Pot!
[7] => filename.jpg
)
The explode() function (docs here), splits a string according to a "delimiter" that you provide it. In this example I have use the / (slash) character.
So you see - you can just grab the values at 5th and 6th index to get the date values.

Categories