Get range letter and number with php - php

how can I get range for bottom string in php?
M0000001:M0000100
I want result
M0000001
M0000002
M0000003
..
..
..
M0000100
this is what i do
<?php
$string = "M0000001:M0000100";
$explode = explode(":",$string );
$text_one = $explode[0];
$text_two = $explode[1];
$range = range($text_one,$text_two);
print_r($range);
?>
So can anyone help me with this?

This is one of many ways you could do this and this is a little verbose but hopefully it shows you some "steps" to take.
It doesn't check for the 1st number being bigger than the 2nd.
It doesn't check your Range strings start with a "M".
It doesn't have all of the required comments.
Those are things for you to consider and work out...
<?php
$string = "M00000045:M000099";
echo generate_range_from_string($string);
function generate_range_from_string($string) {
// First explode the two strings
$explode = explode(":", $string);
$text_one = $explode[0];
$text_two = $explode[1];
// Remove the Leading Alpha character
$range_one = str_replace('M', '', $text_one);
$range_two = str_replace('M', '', $text_two);
$padding_length = strlen($range_one);
// Build the output string
$output = '';
for ( $index = (int) $range_one; $index <= (int) $range_two; $index ++ ) {
$output .= 'M' . str_pad($index, $padding_length, '0', STR_PAD_LEFT) . '<br>';
}
return $output;
}
The output lists a String in the format you have specified in the question. So this is based solely upon that.
This could undergo a few more revisions to make it more function like, as I'm sure some folks will pick out!

Related

Translate phrase with more than 1 singular/plural value

I have the following phrase and want to translate it.
$lifeTime = 'Expires in '.$days.($days == 1 ? ' day ':' days ' ).$h.(($h == 1 ? ' hour ':' hours ' ));
My question is: will I need to split the phrase, translate separated and concatenate them ? Is there a way to __n() function accept multiple "instances" of singular/plural with their respective counts on a single phrase ?
A bit confusing. A example to make it clear:
__('I have %s eggs and %s milk boxes', $eggs, $milk)
This will not have singular and plural form. Can I make it translate the entire phrase without having to split it in two __n() function calls ?
If you know beforehand what words might come in your strings you could do as follows:
// the preperation/setup
$translations = Array();
$translations['hours']['search'] = "%hour";
$translations['hours']['inflections'] = Array("hour", "hours");
$translations['milk']['search'] = "%milk";
$translations['milk']['inflections'] = Array("milk bottle", "bottles of milk");
// add what else you might need
function replaceWithPlurals($heystack, $translations) {
foreach ($translations as $key => $vals) {
$heystack = str_replace($vals['search'], $vals['cnt']." ".$vals['inflections'][usePlural($vals['cnt'])], $heystack);
}
return $heystack;
}
function usePlural($cnt) {
if($cnt==1) return 0;
else return 1;
}
// dynamic vars
$heystack = "I drank %milk in %hour";
$hours = 1;
$milk = 2;
$translations['hours']['cnt'] = $hours;
$translations['milk']['cnt'] = $milk;
// the actual usage
echo replaceWithPlurals($heystack, $translations);
overall that's quite a lot of preperation if you would only need that for 4 specific occations. But if you regular use it I hope that will help.

reorder / rewrap bbcodes

I'm trying to reorder the BBCodes but I failed
so
[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶ ̶-̶ ̶w̶r̶o̶n̶g̶ ̶o̶r̶d̶e̶r̶ ̶ ̶
I̶ ̶w̶a̶n̶t̶ ̶i̶t̶ ̶t̶o̶ ̶b̶e̶:̶ ̶
̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶u̶]̶[̶/̶i̶]̶[̶/̶b̶]̶ ̶-̶ ̶r̶i̶g̶h̶t̶ ̶o̶r̶d̶e̶r̶
PIC:
I tried with
<?php
$string = '[b][i][u]foo[/b][/u][/i]';
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is');
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]');
echo preg_replace($search, $replace, $string);
?>
OUTPUT: [b][i][u]foo[/b][/u][/i]
any suggestions ? thanks!
phew, spent awhile thinking of the logic to do this. (feel free to put it in a function)
this only works for the scenario given. Like other users have commented it's impossible. You shouldn't be doing this. Or even on server side. I'd use a client side parser just to throw a syntax error.
supports [b]a[i]b[u]foo[/b]baa[/u]too[/i]
and bbcode with custom values [url=test][i][u]foo[/url][/u][/i]
Will break with
[b] bold [/b][u] underline[/u]
And [b] bold [u][/b] underline[/u]
//input string to be reorganized
$string = '[url=test][i][u]foo[/url][/u][/i]';
echo $string . "<br />";
//search for all opentags (including ones with values
$tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/";
preg_match_all($tagsearch, $string, $tags);
//search for all close tags to store them for later
$closetagsearch = "/(\[\/([A-Za-z]+)\])/is";
preg_match_all($closetagsearch, $string, $closetags);
//flip the open tags for reverse parsing (index one is just letters)
$tags[1] = array_reverse($tags[1]);
//create temp var to store new ordered string
$temp = "";
//this is the last known position in the original string after a match
$last = 0;
//iterate through each char of the input string
for ($i = 0, $len = strlen($string); $i < $len; $i++) {
//if we run out of tags to replace/find stop looping
if (empty($tags[1]) || empty($closetags[1]))
continue;
//this is the part of the string that has no matches
$good = substr($string, $last, $i - $last);
//next closing tag to search for
$next = $closetags[1][0];
//how many chars ahead to compare against
$scope = substr($string, $i, strlen($next));
//if we have a match
if ($scope === "$next") {
//add to the temp variable with a modified
//version of an open tag letter to become a close tag
$temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0);
//remove the first key/value in both arrays
array_shift($tags[1]);
array_shift($closetags[1]);
//update the last known unmatched char
$last += strlen($good . $scope);
}
}
echo $temp;
Please also note: it might be the users intention to nest the tags out of order :X

Php replace 2 characters with 2 other random ones

I want to swap 2 characters in a string with 2 other ones.
Start string = "`bHello `!how `Qare `%you."
Random string = "1234567890abcdefghijklmnopqrstuvwxyz!£$%^&#"
How do i swap `b `! `Q `% with random ones so it looks something like this
End result string = "`4Hello `^how `$are `#you."
I have tried this so far
I tried so far
$out = "`vHow `!are `#you."
$patterns = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`#","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");
$pretest = array("`1","`J","`2","`3","`4","`5","`6","`7","`!","`$","`%","`^","`&","`)","`~","`#","`#","`q","`e","`y","`t","`p","`j","`k","`l","`M","`x","`v","`m","`Q","`E","`R","`T","`Y","`P","`G","`K","`L","`X","`V");
$tempstr = $pretest[rand(0, strlen($pretest)-1)];
$substs = "`".$tempstr;
$out = preg_replace($patterns, $substs, $out);
However the end result is
$out = "`%How `%are `%you."
it picks only 1 random and changes them all to that one.
<?php
function randomChar() {
$rand = "1234567890abcdefghijklmnopqrstuvwxyz";
return substr($rand, rand(0, strlen($rand)), 1);
}
echo preg_replace_callback("/`./", 'randomChar', "`bHello `!how `Qare `%you.");

PHP Image counter number formatting

I'm building a counter that counts and displays on a web page the number of images in a certain directory.
The code I'm currently using is this:
<?
$d = opendir("images/myimagefolder");
$count = 0;
$min_digits = 7;
while(($f = readdir($d)) !== false)
if(ereg('.jpg$', $f))
++$count;
closedir($d);
if ($min_digits)
{
$count = sprintf('%0'.$min_digits.'f', $count);
}
$number = $count;
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split($formattedNumber, 3);
$formattedNumber = implode(",", $formattedNumber);
print "$formattedNumber";
?>
This works well and outputs a number like the following: 000,000,5
What I am wanting is to have the separating commas occur every 3 digits from the right not the left, so it would appear as 0,000,005
How would this this be done?
I have tried a number of modifications to my sprintf and str_split code but nothing has worked so far. Any help would be greatly appreciated!
<?php
//image count
$images=count(glob("images/myimagefolder/*.jpg"));
//padding
$images=sprintf("%07s",$images);
//commas
$images=strrev(implode(",",str_split(strrev($images),3)));
//outputs 0,000,005
echo $images;
?>
Had a bit of fun coming up with the shortest possible way to accomplish your solution. :)
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split(strrev($formattedNumber), 3);
for (i=0;i<count($formattedNumber); i++)
$formattedNumber[i] = strrev($formattedNumber[i]);
$formattedNumber = implode(",", array_reverse($formattedNumber));
Drop the last four lines. All you need is 'print number_format ($count);'
http://php.net/manual/en/function.number-format.php
Edit, the above won't work with the leading 0's
I found this in the comments on the php site. A little regex magic should do it in one line.
print preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$count);
Here's my take with arrays:
$num = sprintf("%07d", 5);
$digits = str_split($num, 1);
$digits = array_reverse($digits);
$chunks = array_map('array_reverse', array_reverse(array_chunk($digits, 3)));
$concat_chunks = array();
foreach ($chunks as $chunk) {
$concat_chunks[] = join('', $chunk);
}
$output = join(',', $concat_chunks);
print $output;

Replacing last x amount of numbers

I have a PHP variable that looks a bit like this:
$id = "01922312";
I need to replace the last two or three numbers with another character. How can I go about doing this?
EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:
$new = "01922xxx";
Try this:
$new = substr($id, 0, -3) . 'xxx';
Result:
01922xxx
You can use substr_replace to replace a substring.
$id = substr_replace($id, 'xxx', -3);
Reference:
http://php.net/substr-replace
function replaceCharsInNumber($num, $chars) {
return substr((string) $num, 0, -strlen($chars)) . $chars;
}
Usage:
$number = 5069695;
echo replaceCharsInNumber($number, 'xxx'); //5069xxx
See it in action here: http://codepad.org/XGyVQ1hk
Strings can be treated as arrays, with the characters being the keys:
$id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero.
$id_str = strval($id);
for ($i = 0; $i < count($id_str); $i++)
{
print($id_str[$i]);
}
This should output your original number. Now to do stuff with it, treat it as a normal array:
$id_str[count($id_str) - 1] = 'x';
$id_str[count($id_str) - 2] = 'y';
$id_str[count($id_str) - 3] = 'z';
Hope this helps!
Just convert to string and replace...
$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';
We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.
Solution:
$start_time = '1030';
$pattern = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);
//result: 1050

Categories