Dissecting a string - php

I suspect that this has been asked before, but I have no idea what it's actually called, so I couldn't find anything.
I am creating a browser based game in which the player has a 10x10 grid. Each grid square has a few aspects to it, some as binary flags and other as hex values.
To store this information in an array, I want a given cell to contain the following:
"9A0101" where 9A is the tile type, and the 0s and 1s are binary flags about that map tile.
I want to be able to take "9A0101" and split it into "9A", "0", "1", "0", and "1" as separate variables.
TLDR:
How do I slice up a string in PHP? The string will always be the same length, and the parts where I want to cut it will always be at the same offsets.

use substr() to get the parts of string
<?php
echo substr('9A0101', 0,2); // 9A
echo substr('9A0101', 2, 1); // 0
echo substr('9A0101', 3, 1); // 1
echo substr('9A0101', 4, 1); // 0
echo substr('9A0101', 5, 1); // 1
?>

what about substr() ? :
<?php
$str = '9A0101';
echo substr($str,0,2);
echo substr($str,2,1);
echo substr($str,3,1);
echo substr($str,4,1);
echo substr($str,5,1);
?>

You can the substr() function
<?php
$str = "9A0101";
$arr = Array();
$arr[0] = substr($str, -6, 2);
$arr[1] = substr($str, -4, 1);
$arr[2] = substr($str, -3, 1);
$arr[3] = substr($str, -2, 1);
$arr[4] = substr($str, -1, 1);
foreach($arr as $key => $val) {
echo($key . "=>" . $val . '<br/>');
}
?>

Or maybe can use the str_split() function.
$str = "9A0101";
//splitting the string
$array = str_split($str, 2);
var_dump($array);

If you are looking for a single function call, regex can serve you well.
preg_split('~(^..|.)\K~', $string);
The above will split the string on the zero-width position after the first two characters of the string or each subsequent character. \K means forget what is already matched.
If you want to save the 5 values as individual variables, then you can use list() or array destructuring syntax. Demo
[$type, $one, $two, $three, $four] = preg_split('~(^..|.)\K~', $string);
If you wish, you can even access the single byte characters by their string offset. Demo
$type = $string[0] . $string[1];
$one = $string[2];
$two = $string[3];
$three = $string[4];
$four = $string[5];

Related

encode string in PHP as a=1,b=2 and so on

I want to create PHP function to encode any string just with following rule.
a=1; b=2; c=3;.....y=25;z=26;
for eg.
If my string is "abc" then my encoded data will be "123".
We can use $key=>$value array but it will iterate 26 times for every letter!!
Use some delimiter so that you can identify separate characters. You can try this.
$chars = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$str = "acd";
$encoded = array();
for ($i = 0; $i < strlen($str); $i++) {
$encoded[] = $chars[$str[$i]];
}
echo implode('|', $encoded);
Output
1|3|4
function encodedString($your_string)
$alpha_arr = range("A", "Z");
$your_string = strtoupper($your_string);
$encoded = "";
for($i=0; $i<strlen($your_string); $i++)
{
$strOne = substr($your_string, $i, 1);
if (in_array($strOne, $alpha_arr))
{
$encoded .= array_search($strOne, $alpha_arr)+1;
}
}
return $encoded;
}
You should have a padded encoding number to avoid confusions, with an array such as:
$converter = array('a' => '01', 'b' => '02' ...);
then go through each letter of the original string and construct your encoded string accessing the $converter array by key ('a', 'b' ... 'z').
you can also use str_replace to loop through the converter array and replace each character. Using str_replace you have at most N iterations, where N is the number of items in the converter array, regardless of the original string dimension.
The ord() method outputs the ascii value. now you can subtract 64 and 96 based on the text case to get the corresponding values. You will need no iterations or loop or anything. use a change case function and get the ascii value. the subtract the constant.
More details about ord method here

How to extract the value at the end of a string in php

In my php code I have an array of variables starting with a word followed by an (random) number:
x[0] = 'justaword8'
x[1] = 'justaword5'
x[2] = 'justaword4'
etc.
I know i must use a foreach loop, but how to extract the figures at the end of each word? (I assume I could use preg_match() but have no idea how specify that function exactly?)
Since the number varies in length, between one or two digits, you can use preg_match() like this:
foreach( $array as $x) {
preg_match( '/(\d{1,2})$/', $x, $match);
echo "The number is: " . $match[1];
}
However, since the prefix is known ahead of time, just remove it directly (as per Marc B's comment, with an example usage):
$prefix = "justaword";
$length = strlen( $prefix);
foreach( $array as $x) {
echo "The number is: " . substr( $x, $length);
}
Try using this: Working eval.in (This will work for one digit)
foreach($x as $key => $value)
echo substr($value,-1);
I've updated for the case of two digits, it looks a bit crude without regex however works just fine if for some reason you don't want to use regex: (Working eval.in)
<?php
$x[0] = 'justaword8';
$x[1] = 'justaword52';
$x[2] = 'justaword4';
foreach($x as $key => $value){
$y = substr($value,'-2:');
if(is_numeric($y)) // if last 2 chars are number
echo $y; // return them
else
echo substr($y,1); // return only the last char
}
?>
If "justaword" is constant you can just use str_replace('justaword','',$x[0]); to remove it.
you can try this.its only for one digit
$str="justaword5";
echo $last_dig=substr($str,strlen($str)-1,strlen($str));
Using str_replace to trim off the prefix.
$prefix = "justaword";
$words = array("justaword8", "justaword4", "justaword500");
$numbers = array();
foreach ($words as $word) {
$numbers[] = str_replace($prefix, "", $word);
}
var_dump($numbers); // gives 8, 4, 500
Code:
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
output:
`Hll Wrld f PHP`
Instead what you should do is let array be the array of all 26 characters.
After all the characters are replaced by a ' ' you can then directly convert a string to number!

preg_split() 2 letters and decimal

I have a string and this string should be an array.
But the first 2 letters are variable and I need the 5 next digits (whether empty or not). The last 5 digits are numeric with a decimal point or empty ( $string="AB3 . ";)
An example:
$string = "AB10.00";
$arr[0] = "AB";
$arr[1] = "10.00";
I would like to use preg_split() for this.
You mean substr() ?
$string = "AB10.00";
$arr[0] = substr($string, 0, 2); // $arr[0] == 'AB'
$arr[1] = substr($string, 2); // $arr[1] == '10.00'

Add +1 to a string obtained from another site

I have a string I get from a website.
A portion of the string is "X2" I want to add +1 to 2.
The entire string I get is:
20120815_00_X2
What I want is to add the "X2" +1 until "20120815_00_X13"
You can do :
$string = '20120815_00_X2';
$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);
$incremented = $concat . ($num + 1);
echo $incremented;
For more informations about substr() see => documentation
You want to find the number at the end of your string and capture it, test for a maximum value of 12 and add one if that's the case, so your pattern would look something like:
/(\d+)$/ // get all digits at the end
and the whole expression:
$new = preg_replace('/(\d+)$/e', "($1 < 13) ? ($1 + 1) : $1", $original);
I have used the e modifier so that the replacement expression will be evaluated as php code.
See the working example at CodePad.
This solution works (no matter what the number after X is):
function myCustomAdd($string)
{
$original = $string;
$new = explode('_',$original);
$a = end($new);
$b = preg_replace("/[^0-9,.]/", "", $a);
$c = $b + 1;
$letters = preg_replace("/[^a-zA-Z,.]/", '', $a);
$d = $new[0].'_'.$new[1].'_'.$letters.$c;
return $d;
}
var_dump(myCustomAdd("20120815_00_X13"));
Output:
string(15) "20120815_00_X14"

How to insert a string inside another string?

Just looked at function
str_pad($input, $pad_length, $pad_str, [STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH])
which helps to pad some string on left, right or on both sides of a given input.
Is there any php function which I can use to insert a string inside an input string?
for example ..
$input = "abcdef";
$pad_str = "#";
so if I give insert index 3, it inserts "#" after first 3 left most characters and $input becomes "abc#def".
thanks
You're looking for a string insert, not a padding.
Padding makes a string a set length, if it's not already at that length, so if you were to give a pad length 3 to "abcdef", well it's already at 3, so nothing should happen.
Try:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
PHP manual on substr_replace
you need:
substr($input, 0, 3).$pad_str.substr($input, 3)
Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.
I'll leave it here so it's not wasted.
You can use regular expressions and some calculation to get your desired result (you probably could make it with pure regexp, but that would be more complex and less readable)
vinko#mithril:~$ more re.php
<?php
$test1 = "123123123";
$test2 = "12312";
echo puteveryXcharacters($a,"#",3);
echo "\n";
echo puteveryXcharacters($b,"#",3);
echo "\n";
echo puteveryXcharacters($b,"$",3);
echo "\n";
function puteveryXcharacters($str,$wha,$cnt) {
$strip = false;
if (strlen($str) % $cnt == 0) {
$strip = true;
}
$tmp = preg_replace('/(.{'.$cnt.'})/',"$1$wha", $str);
if ($strip) {
$tmp = substr($tmp,0,-1);
}
return $tmp;
}
?>
vinko#mithril:~$ php re.php
123#123#123
123#12
123$12

Categories