Php check exist have how many random int numbers in string - php

I have rand function like;
$mynumbers = rand(1111,9999);
echo $mynumbers;
Example output is
3582
and I have another strings
$mystring = "Ja9Js78I4PhXiF464R6s7ov8IUF"; (Have 1 number, must be turn 1 (only 8 have))
$mystring2 = "Ja3Js73I4P1X5iF564R8s2ov8IUF"; (Have 4 numbers, must be turn 4 (have all of them))
And i want to know this with function ;
$mystring is have, how many numbers ? inside $mynumbers and how many time ? passed when this process ? How can i do it ?

per your last comment. Treat the integer as a string (PHP is good at that). And iterate by character.
<?php
$foo = '1234';
$mystring = [];
$mystring[] = 'A1B2KLDLDF3'; //3
$mystring[] = 'XXXX4XXXX'; //1
foreach ($mystring as $key => $string) {
echo "mystring {$key}: ";
$c = 0;
foreach(str_split($foo) as $char) {
$c = $c + substr_count($string, $char);
}
echo $c . '<br/>';
}
mystring 0: 3
mystring 1: 1
As this is PHP you also need to be aware of mb_ multibyte functions. See: http://php.net/manual/en/function.mb-substr-count.php
Update:
Sounds like you should clean up the string you are checking then if you want to discard all duplicates... Could then of course use a substr or other method perhaps more performant than substr_count.
$mystring = 'A111111B2KLDLDF333'; //3
$mystring = implode('',array_unique(str_split($mystring)));
//gives 'A1B2KLDF3'

Related

Is it possible to cut a word in parts? [PHP]

I would like to ask if it is possible to cut a word like
"Keyboard" in multiple strings, in PHP?
I want the string to be cut whenever a / is in it.
Example:
String: "Key/boa/rd"
Now I want that the cut result look like this:
String1: "Key"
String2: "boa"
String3: "rd"
You can use the PHP explode function. So, if your string was "Key/boa/rd", you would do:
explode('/', 'Key/boa/rd');
and get:
[
"Key",
"boa",
"rd",
]
It's unclear from your question, but if you don't want an array (and instead would like variables) you can use array destructuring like so:
[$firstPart, $secondPart, $thirdPart] = explode('/', 'Key/boa/rd');
However, if the string only had one / then that approach could lead to an exception being thrown.
The answer by Nathaniel assumes that your original string contains / characters. It is possible that you only used those in your example and you want to split the string into equal-length substrings. The function for that is str_split and it looks like:
$substrings = str_split($original, 3);
That will split the string $original into an array of strings, each of length 3 (except the very last one if it doesn't divide equally).
You can travel through the line character by character, checking for your delimeter.
<?php
$str = "Key/boa/rd";
$i = $j = 0;
while(true)
{
if(isset($str[$i])) {
$char = $str[$i++];
} else {
break;
}
if($char === '/') {
$j++;
} else {
if(!isset($result[$j])) {
$result[$j] = $char;
} else {
$result[$j] .= $char;
}
}
}
var_export($result);
Output:
array (
0 => 'Key',
1 => 'boa',
2 => 'rd',
)
However explode, preg_split or strtok are probably the goto Php functions when wanting to split strings.

How to take multiple standard input in a single line using php command line

like Input is:
3
1 2
2 3
4 5
I have to take those input in given style. Here (1 and 2), (2 and 3) and (4 and 5) have to take in one line as a input.
Here is my code snippet.
<?php
header('Content-Type: text/plain');
$testCase = (int) fgets(STDIN);
while($testCase--) {
$myPosition = (int) fgets(STDIN);
$liftPosition = (int) fgets(STDIN);
}
Implementation in C++
int main()
{
int testcase, myPos, liftPos;
cin >> testcase;
while(testcase--)
{
cin >> myPos >> liftPos;
}
}
So, how can implement the C++ code in PHP ?
Equivalent in PHP would be:
<?php
header('Content-Type: text/plain');
$testCase = (int) fgets(STDIN);
while($testCase--) {
$input = fgets(STDIN);
$inputParts = preg_split("/[\s]+/",$input);
$myPosition = (int)$inputParts[0];
$liftPosition = (int)$inputParts[1];
}
This is because the C-type shift operator in your example takes in both numbers as separate numbers. It delimits automatically with the whitespace character. Therefore you need to split the input string in PHP manually.
Actually, the problem is in the following line:
$myPosition = (int) fgets(STDIN);
Here, the explicit conversion to int is discarding the value after space, so when you give 1 2 as the input in the command line the (int) is turning it into 1 and you are losing the other character.
$arr = [];
$testCase = (int) fgets(STDIN);
while ($testCase--) {
list($a, $b) = explode(' ', fgets(STDIN));
$arr[] = $a.' '.$b;
}
print_r($arr);
The above solution works because I've removed the (int) from the beginning of the fgets. Also note that, I'm using list($a, $b) here, which will actually create two variable $a and $b in the current scope so I'm always assuming that, you'll use two separate numbers (i.e: 1 2), otherwise you can use $inputParts = preg_split("/[\s]+/",$input) or something else with explode to form the array from input from console.

How to truncate a delimited string in PHP?

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

How to find first non-repetitive character from a string?

I've spent half day trying to figure out this and finally I got working solution.
However, I feel like this can be done in simpler way.
I think this code is not really readable.
Problem: Find first non-repetitive character from a string.
$string = "abbcabz"
In this case, the function should output "c".
The reason I use concatenation instead of $input[index_to_remove] = ''
in order to remove character from a given string
is because if I do that, it actually just leave empty cell so that my
return value $input[0] does not not return the character I want to return.
For instance,
$str = "abc";
$str[0] = '';
echo $str;
This will output "bc"
But actually if I test,
var_dump($str);
it will give me:
string(3) "bc"
Here is my intention:
Given: input
while first char exists in substring of input {
get index_to_remove
input = chars left of index_to_remove . chars right of index_to_remove
if dupe of first char is not found from substring
remove first char from input
}
return first char of input
Code:
function find_first_non_repetitive2($input) {
while(strpos(substr($input, 1), $input[0]) !== false) {
$index_to_remove = strpos(substr($input,1), $input[0]) + 1;
$input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1);
if(strpos(substr($input, 1), $input[0]) == false) {
$input = substr($input, 1);
}
}
return $input[0];
}
<?php
// In an array mapped character to frequency,
// find the first character with frequency 1.
echo array_search(1, array_count_values(str_split('abbcabz')));
Python:
def first_non_repeating(s):
for i, c in enumerate(s):
if s.find(c, i+1) < 0:
return c
return None
Same in PHP:
function find_first_non_repetitive($s)
{
for($i = 0; i < strlen($s); $i++) {
if (strpos($s, $s[i], $i+1) === FALSE)
return $s[i];
}
}
Pseudocode:
Array N;
For each letter in string
if letter not exists in array N
Add letter to array and set its count to 1
else
go to its position in array and increment its count
End for
for each position in array N
if value at potition == 1
return the letter at position and exit for loop
else
//do nothing (for clarity)
end for
Basically, you find all distinct letters in the string, and for each letter, you associate it with a count of how many of that letter exist in the string. then you return the first one that has a count of 1
The complexity of this method is O(n^2) in the worst case if using arrays. You can use an associative array to increase it's performance.
1- use a sorting algotithm like mergesort (or quicksort has better performance with small inputs)
2- then control repetetive characters
non repetetive characters will be single
repetetvives will fallow each other
Performance : sort + compare
Performance : O(n log n) + O(n) = O(n log n)
For example
$string = "abbcabz"
$string = mergesort ($string)
// $string = "aabbbcz"
Then take first char form string then compare with next one if match repetetive
move to the next different character and compare
first non-matching character is non-repetetive
This can be done in much more readable code using some standard PHP functions:
// Count number of occurrences for every character
$counts = count_chars($string);
// Keep only unique ones (yes, we use this ugly pre-PHP-5.3 syntax here, but I can live with that)
$counts = array_filter($counts, create_function('$n', 'return $n == 1;'));
// Convert to a list, then to a string containing every unique character
$chars = array_map('chr', array_keys($counts));
$chars = implode($chars);
// Get a string starting from the any of the characters found
// This "strpbrk" is probably the most cryptic part of this code
$substring = strlen($chars) ? strpbrk($string, $chars) : '';
// Get the first character from the new string
$char = strlen($substring) ? $substring[0] : '';
// PROFIT!
echo $char;
$str="abbcade";
$checked= array(); // we will store all checked characters in this array, so we do not have to check them again
for($i=0; $i<strlen($str); $i++)
{
$c=0;
if(in_array($str[$i],$checked)) continue;
$checked[]=$str[$i];
for($j=$i+1;$j<=strlen($str);$j++)
{
if($str[$i]==$str[$j])
{
$c=1;
break;
}
}
if($c!=1)
{
echo "First non repetive char is:".$str[$i];
break;
}
}
This should replace your code...
$array = str_split($string);
$array = array_count_values($array);
$array = array_filter($array, create_function('$key,$val', 'return($val == 1);'));
$first_non_repeated_letter = key(array_shift($array));
Edit: spoke too soon. Took out 'array_unique', thought it actually dropped duplicate values. But character order should be preserved to be able to find the first character.
Here's a function in Scala that would do it:
def firstUnique(chars:List[Char]):Option[Char] = chars match {
case Nil => None
case head::tail => {
val filtered = tail filter (_!=head)
if (tail.length == filtered.length) Some(head) else firstUnique(filtered)
}
}
scala> firstUnique("abbcabz".toList)
res5: Option[Char] = Some(c)
And here's the equivalent in Haskell:
firstUnique :: [Char] -> Maybe Char
firstUnique [] = Nothing
firstUnique (head:tail) = let filtered = (filter (/= head) tail) in
if (tail == filtered) then (Just head) else (firstUnique filtered)
*Main> firstUnique "abbcabz"
Just 'c'
You can solve this more generally by abstracting over lists of things that can be compared for equality:
firstUnique :: Eq a => [a] -> Maybe a
Strings are just one such list.
Can be also done using array_key_exists during building an associative array from the string. Each character will be a key and will count the number as value.
$sample = "abbcabz";
$check = [];
for($i=0; $i<strlen($sample); $i++)
{
if(!array_key_exists($sample[$i], $check))
{
$check[$sample[$i]] = 1;
}
else
{
$check[$sample[$i]] += 1;
}
}
echo array_search(1, $check);

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