Since I am still new to PHP, I am looking for a way to find out how to get a specific character from a string.
Example:
$word = "master";
$length = strlen($word);
$random = rand(1,$length);
So let's say the $random value is 3, then I would like to find out what character the third one is, so in this case the character "s". If $random was 2 I would like to know that it's a "a".
I am sure this is really easy, but I tried some substr ideas for nearly an hour now and it always fails.
Your help would be greatly appreciated.
You can use substr() to grab a portion of a string starting from a point and going length. so example would be:
substr('abcde', 1, 1); //returns b
In your case:
$word = "master";
$length = strlen($word) - 1;
$random = rand(0,$length);
echo substr($word, $random, 1);//echos single char at random pos
See it in action here
You can use your string the same like 0-based index array:
$some_string = "apple";
echo $some_string[2];
It'll print 'p'.
or, in your case:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
echo $word[$random];
Try this simply:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
if($word[$random] == 's'){
echo $word[$random];
}
Here I used 0 because $word[0] is m so that we need to subtract one from strlen($word) for getting last character r
Use substr
$GetThis = substr($myStr, 5, 5);
Just use the same values for the same or different if you want multiple characters
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
$GetThis = substr($word, $random, $random);
As noted in my comment (I overlooked as well) be sure to start your rand at 0 to include the beginning of your string since the m is at place 0. If we all overlooked that it wouldn't be random (as random?) now would it :)
You can simply use $myStr{$random} to obtain the nth character of the string.
Related
So while i was doing my homework i stuck on one point.
The excercise is based on making a function which checks if $word is a palindrome, from my tests $L works and is moving forward to right side of the word ($L starts from left, $R from right)
but $R is not working at all, if $R is swapped by a number - it works. If $R is printed, it shows right number - 5.
$word = "madam";
function palindrome($s)
{
$i = intval(strlen($s) / 2);
$L = 0;
$R = strlen($s);
$pal = true;
for($i; $i>0; $i--)
{
if($s[$L] != $s[$R]) $pal=false;
$L++;
$R--;
}
if($pal==true)
print("palindrome");
else
print("not a palindrome");
}
palindrome($word);
I expect to make $R an value, i suspect that PHP sees it as a string, not an integer, but i don't know why. I would be very happy if someone helped me with that.
If you consider string as char table, index starts at 0, but strlen count from 1 so if you have 'madam' then strlen() returns 5 but last chatacter is on $s[4], simply use:
$R = strlen($s)-1;
As a quick, off the top of my head sort of idea... no loops, just some simple string splitting, this works to check if the given string ($s) is a palindrome.
function palindrome($s) {
// split the string in two
$left = substr($s, 0, floor(strlen($s)/2));
$right = substr($s, 0-strlen($left));
// if the left half matches the REVERSE of the right
// you've got a palindrome
return $left === strrev($right);
}
$word = "madam";
echo palindrome($word) ? "Yup" : "Nope";
Basically, it just chops the word in half - reverses the right half and compares it to the left. If they match, it's a palindrome - currently it's case-sensitive though so "Madam" won't be a palindrome but that can be easily tweaked by lower-casing the whole thing first.
I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test
For the following code :
<?php
$word = 'SEKISUI';
// echo substr($word,0,-6)."<br>";
$length = (strlen($word)+1)-14;
$urut = 0;
for($i=$length;$i<1;$i++){
echo substr($word,$urut,$i).'<br>';
// echo $urut."-".$i."-".'<br>'; // Check Value
$urut++;
}
?>
Result :
S
E
K
I
S
U
why the letter "i" doesn't appear?
what is wrong with my code?
The result should look like:
S
E
K
I
S
U
I
Thank you for your attention...
I don't know if you NEED to use a 'for loop', but there is a better way to split a string into single characters.
Once you have the array you can do any operation to it, also join() the items in the array with a "\< br>" separator.
Try the following:
$word = 'SEKISUI';
$result = str_split($word);
$altogether = join("<br>",$result);
Not sure why you like the subtracting the length and not deal with positive numbers as much as possible.
In the syntax of substr(string,start,length),
Optional. Specifies the length of the returned string. Default is to
the end of the string. A positive number - The length to be returned
from the start parameter Negative number - The length to be returned
from the end of the string
So essentially your pointer on the end character is nevel counted.
if you run echo substr($word,0,-1)."<br>";, you will not get the end character as it is place of the start for the negative substr.
However, changing the substr length to 1 will give a valid string and not null or empty string
$word = 'SEKISUI';
// echo substr($word,0,-6)."<br>";
$length = (strlen($word)+1)-14;
$urut = 0;
for($i=$length;$i<1;$i++){
echo substr($word,$urut,1).'<br>';
// echo $urut."-".$i."-".'<br>'; // Check Value
$urut++;
}
However, I would prefer this approach, as this is much simpler.
$word = 'SEKISUI';
//echo substr($word,1,1)."<br>";
$length = strlen($word);
$urut = 0;
for($i = $urut; $i <= $length; $i++){
echo substr($word,$i,1).'<br>';
}
I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number
assuming $string is your "0101" string, you could just do $m1 = '1'.$string;
My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}
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