How to add <br> in string with substr() - php

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>';
}

Related

Remove lowercase letter if it is followed by an uppercase letter

The goal is to get from string $a="NewYork" new string without lowercase that stands before uppercase.
In this example, we should get output "NeYork"
I tried to do this through positions of small and big letters in ASCII table, but it doesn't work. I'm not sure is it possible to to do this in similar way, through positions in ASCII table.
function delete_char($a)
{
global $b;
$a = 'NewYork';
for($i =0; $i<strlen($a); $i++)
{
if( ord($a[$i])< ord($a[$i+1])){//this solves only part of a problem
chop($a,'$a[$i]');
}
else{
$b.=$a[$i];
}
}
return $b;
}
This is something a regular expression handles with ease
<?php
$a ="NewYorkNewYork";
$reg="/[a-z]([A-Z])/";
echo preg_replace($reg, "$1", $a); // NeYorNeYork
The regular expression searches for a lower case letter followed by an upper case letter, and captures the upper case one. preg_replace() then replace that combination with just the captured letter ($1).
See https://3v4l.org/o43bO
You don't need to capture the uppercase letter and use a backreference in the replacement string.
More simply, match the lowercase letter then use a lookahead for an uppercase letter -- this way you only replace the lowercase character with an empty string. (Demo)
echo preg_replace('~[a-z](?=[A-Z])~', '', 'NewYork');
// NeYork
As for a review of your code, there are multiple issues.
global $b doesn't make sense to me. You need the variable to be instantiated as an empty string within the scope of the custom function only. It more simply should be $b = '';.
The variable and function naming is unhelpful. A function's name should specifically describe the function's action. A variable should intuitively describe the data that it contains. Generally speaking, don't sacrifice clarity for brevity.
As a matter of best practice, you should not repeatedly call a function when you know that the value has not changed. Calling strlen() on each iteration of the loop is not beneficial. Declare $length = strlen($input) and use $length over and over.
$a[$i+1] is going to generate an undefined offset warning on the last iteration of the loop because there cannot possibly be a character at that offset when you already know the length of the string has been fully processed. In other words, the last character of a string will have an offset of "length - 1". There is more than one way to address this, but I'll use the null coalescing operator to set a fallback character that will not qualify the previous letter for removal.
Most importantly, you cannot just check that the current ord value is less than the next ord value. See here that lowercase letters have an ordinal range of 97 through 122 and uppercase letters have an ordinal range of 65 through 90. You will need to check that both letters meet the qualifying criteria for the current letter to be included in the result string.
Rewrite: (Demo)
function removeLowerCharBeforeUpperChar(string $input): string
{
$output = '';
$length = strlen($input);
for ($offset = 0; $offset < $length; ++$offset) {
$currentOrd = ord($input[$offset]);
$nextOrd = ord($input[$offset + 1] ?? '_');
if ($currentOrd < 97
|| $currentOrd > 122
|| $nextOrd < 65
|| $nextOrd > 90
){
$output .= $input[$offset];
}
}
return $output;
}
echo removeLowerCharBeforeUpperChar('MickMacKusa');
// MicMaKusa
Or with ctype_ functions: (Demo)
function removeLowerCharBeforeUpperChar(string $input): string
{
$output = '';
$length = strlen($input);
for ($offset = 0; $offset < $length; ++$offset) {
$nextLetter = $input[$offset + 1] ?? '';
if (ctype_lower($input[$offset]) && ctype_upper($nextLetter)) {
$output .= $nextLetter; // omit current letter, save next
++$offset; // double iterate
} else {
$output .= $input[$offset]; // save current letter
}
}
return $output;
}
To clarify, I would not use the above custom function in a professional script and both snippets are not built to process strings containing multibyte characters.
Simply, I create new variable $s used for store new string to be returned and a make loop iterate over $a string, I used ctype_upper to check if next character not uppercase append it to $s. at the end i return $s concatenate with last char of string.
function delete_char(string $a): string
{
if(!strlen($a))
{
return '';
}
$s='';
for($i = 0; $i < strlen($a)-1; $i++)
{
if(!ctype_upper($a[$i+1])){
$s.=$a[$i];
}
}
return $s.$a[-1];
}
echo delete_char("NewYork");//NeYork
Something like this maybe?
<?php
$word = 'NewYork';
preg_match('/.[A-Z].*/', $word, $match);
if($match){
$rlen = strlen($match[0]); //length from character before capital letter
$start = strlen($word)-$rlen; //first lower case before the capital
$edited_word = substr_replace($word, '', $start, 1); //removes character
echo $edited_word; //prints NeYork
}
?>

Generate random between alphanumeric min and max in PHP

I am looking for an approach like mt_rand to generate a random value, but between two alphanumeric values instead of integers.
For example, rand(g3j3j4k5, z9kDDkks8f8d).
I tried to convert the alphanumeric values to integers by base_convert. Beside the fact, it is somehow overkill, sometimes the integer is more than 15 digits, and thus not working in PHP rand functions.
NOTE: It is not about making a random string with given length. The value should between two given values, exactly like a random number between min and max integers.
This should work for you:
Here I split $min and $max into an array with str_split() and loop through each character of both arrays with array_map().
There I get the position of the character with strpos() and return a random alphanum character in that particular range. If min is bigger than max I just return a random character from the entire range.
Code:
<?php
function alphanum_rand($min = "", $max = ""){
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$random = array_map(function($minC, $maxC)use($chars){
if(($minKey = strpos($chars, $minC)) < ($maxKey = strpos($chars, $maxC)))
return $chars[mt_rand($minKey, $maxKey)];
else
return $chars[mt_rand(0, strlen($chars))];
}, str_split($min), str_split($max));
return implode("", $random);
}
echo alphanum_rand("g3j3j4k5", "z9kDDkks8f8d");
?>
You could try a simple PHP Function and define a random string alpha numeric and can also include special characters. For loop will do the magic for u :)
function RandomString($size)
{
$chars = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$string = array();
$alphaLength = strlen($chars) - 1;
for ($i = 0; $i < $size; $i++) {
$n = rand(0, $alphaLength);
$string[] = $chars[$n];
}
return implode($string);
}
and simple call it with the size you need.
<?php
echo RandomString(5); // Length of strings
?>

PHP: Shift characters of string by 5 spaces? So that A becomes F, B becomes G etc

How can I shift characters of string in PHP by 5 spaces?
So say:
A becomes F
B becomes G
Z becomes E
same with symbols:
!##$%^&*()_+
so ! becomes ^
% becomes )
and so on.
Anyway to do this?
The other answers use the ASCII table (which is good), but I've got the impression that's not what you're looking for. This one takes advantage of PHP's ability to access string characters as if the string itself is an array, allowing you to have your own order of characters.
First, you define your dictionary:
// for simplicity, we'll only use upper-case letters in the example
$dictionary = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Then you go through your input string's characters and replace each of them with it's $position + 5 in the dictionary:
$input_string = 'STRING';
$output_string = '';
$dictionary_length = strlen($dictionary);
for ($i = 0, $length = strlen($input_string); $i < $length; $i++)
{
$position = strpos($dictionary, $input_string[$i]) + 5;
// if the searched character is at the end of $dictionary,
// re-start counting positions from 0
if ($position > $dictionary_length)
{
$position = $position - $dictionary_length;
}
$output_string .= $dictionary[$position];
}
$output_string will now contain your desired result.
Of course, if a character from $input_string does not exist in $dictionary, it will always end up as the 5th dictionary character, but it's up to you to define a proper dictionary and work around edge cases.
Iterate over characters and, get ascii value of each character and get char value of the ascii code shifted by 5:
function str_shift_chars_by_5_spaces($a) {
for( $i = 0; $i < strlen($a); $i++ ) {
$b .= chr(ord($a[$i])+5);};
}
return $b;
}
echo str_shift_chars_by_5_spaces("abc");
Prints "fgh"
Iterate over string, character at a time
Get character its ASCII value
Increase by 5
Add to new string
Something like this should work:
<?php
$newString = '';
foreach (str_split('test') as $character) {
$newString .= chr(ord($character) + 5);
}
echo $newString;
Note that there is more than one way to iterate over a string.
PHP has a function for this; it's called strtr():
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"FGHIJKLMNOPQRSTUVWXYZABCDE" );
Of course, you can do lowercase letters and numbers and even symbols at the same time:
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()_+",
"FGHIJKLMNOPQRSTUVWXYZABCDEfghijklmnopqrstuvwxyzabcde5678901234^&*()_+!##$%" );
To reverse the transformation, just swap the last two arguments to strtr().
If you need to change the shift distance dynamically, you can build the translation strings at runtime:
$shift = 5;
$from = $to = "";
$sequences = array( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
"0123456789", "!##$%^&*()_+" );
foreach ( $sequences as $seq ) {
$d = $shift % strlen( $seq ); // wrap around if $shift > length of $seq
$from .= $seq;
$to .= substr($seq, $d) . substr($seq, 0, $d);
}
$shifted = strtr( $string, $from, $to );

Detect if a string contains any numbers

This is the test.php file:
$string = 'A string with no numbers';
for ($i = 0; $i <= strlen($string)-1; $i++) {
$char = $string[$i];
$message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}
// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));
// function
function codeStyle($string) {
return '<span style="background-color: #eee; font-weight: bold;">' . $string . '</span>';
}
It splits the string character by character and checks if the character is a number or not.
Problem: Its output is always "This variable includes number(s)". Please help me to find the reason.
TIP: When I change range(0,9) to range(1,9) It works correctly (But it can't detect 0).
Use preg_match():
if (preg_match('~[0-9]+~', $string)) {
echo 'string with numbers';
}
Althought you should not use it, as it is much slower than preg_match() I will explain why your original code is not working:
A non numerical character in the string when compared to a number (in_array() does that internally) would be evaluated as 0 what is a number. Check this example:
var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)
Correct would be to use is_numeric() here:
$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
if(is_numeric($string[$i])) {
$keyword = 'includes';
break;
}
}
Or use the string representations of the numbers:
$keyword = 'doesn\'t include';
// the numbers as stings
$numbers = array('0', '1', '2', /* ..., */ '9');
for ($i = 0; $i <= strlen($string)-1; $i++) {
if(in_array($string[$i], $numbers)){
$keyword = 'includes';
break;
}
}
You can just use regexp :
$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';
Better way is using regular expression
<?php
if (preg_match('#[0-9]#',$string)){
$message_keyword = 'includes';
}
else{
$message_keyword = 'desn\'t include';
}
?>
This is because of PHP loose type comparison, you are comparing string with integer, so PHP internally will cast this string to integer, and all character in your string will be casted to 0.
First step to fix your code, will be to create an array of strings instead of integers:
$numbers = array_map(function($n){ return (string)$n; }, range(0,9));
for ($i = 0; $i <= strlen($string)-1; $i++) {
$char = $string[$i];
$message_keyword = in_array($char,$numbers)?'includes' : 'doesn\'t include';
}
This will fix your case, but will not work as you expect it to, since $message_keyword is overwritten on each loop, so will receive message for last character only. If you are aiming to only check if string contains number, you can stop checking after encountering first number:
$message_keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
$char = $string[$i];
if(in_array($char, $numbers)) {
$message_keyword = 'includes';
break; //found, no need to check next
}
}
To have this all logic in more compact form, use regular expresion, as posted by others before.
It's kinda late to answer this question after about 9 years, but If you want to detect integers (and not floats) nothing is better than ctype_digit. Using this function to detect floats with decimal point or other types would results in returning false.
<?php
$number = "123";
$notNumber = "123abc";
var_dump(ctype_digit($number));
var_dump(ctype_digit($notNumber));
?>
Output
bool(true)
bool(false)
array range ( mixed $start , mixed $end [, number $step = 1 ] )
If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.
In your case, you havent mentioned the third parameter that is why it is always set to 1
See Manual here

Finding a character at a specific position of a string

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.

Categories