Get The Number of Sepecific String Inside String - php

if I have a string something like this:
$string = '01122028K,02122028M,03122028K,04122028M,05122028K,06122028P-2,07122028K,08122028P-';
How can I do to get the number of 'K' inside string $string. In this case K would be 4.
I know it can be solved by the help strpos() through out the looping after explode the $string into array. Is any php function to do it in straightforward way?
Thank you.

echo "There are " . substr_count($string, 'K') . " K's in the string";
If you don't want to count K-1 this can be:
echo "There are " . substr_count($string, 'K')-substr_count($string, 'K-') . " K's in the string";
To solve the new problem in the comments:
$string = '01122028K,02122028M,02122028K-1,02122028K-2,03122028K,04122028M,05122028K-1,04122028M,05122028K,06122028P-2,07122028K,08122028P-';
preg_match_all('/K(?:-\d+)?/', $string, $match);
$counts = array_count_values($match[0]);
print_r($counts);
Array
(
[K] => 4
[K-1] => 2
[K-2] => 1
)

Try also this solution:
$string = '01122028K,02122028M,03122028K,04122028M,05122028K,06122028P-2,07122028K,08122028P-';
$strlen = strlen($string);
$count = 0;
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr( $string, $i, 1 );
// $char contains the current character, so do your processing here
if ($char == "K")
$count++:
}
then...
echo $count;
That's not a "straightforward way" BUT I found it useful since it's very flexible and you can manipulate all sort of code on your string.
Good Luck!

Related

Want to iterate a string that after each charater there will be a space in PHP

I want to iterate a string in the manner that after each character there should be a space and there will be new string(word) as per the main string character count.
For example
If I put the string "v40eb" as an input. Then Output be something like below.
v 40eb
v4 0eb
v40 eb
v40e b
OR
In Array form like below.
[0]=>v 40eb[1]=>v4 0eb[2]=>v40 eb[3]=>v40e b
I am using PHP.
Thanks
Well, you can divide the process of putting a space into 2 parts.
Get first part of the substring, append a space.
Get second part of the substring and join them together.
Use substr() to get a substring of a string.
Snippet:
<?php
$str = "v40eb";
$result = [];
$len = strlen($str);
for($i=0;$i<$len;++$i){
$part1 = substr($str,0,$i+1);
if($i < $len-1) $part1 .= " ";
$part2 = substr($str,$i+1);
$result[] = $part1 . $part2;
}
print_r($result);
Demo: https://3v4l.org/XGN0a
You could simply loop over the char positions and use substr to get the two parts for each:
$input = 'v40eb';
$combinations = [];
for ($charPos = 1, $charPosMax = strlen($input); $charPos < $charPosMax; $charPos++) {
$combinations[] = substr($input, 0, $charPos) . ' ' . substr($input, $charPos);
}
print_r($combinations);
Demo: https://3v4l.org/EeT1V
$input = 'v40eb';
for($i = 1; $i< strlen($input); $i++) {
$array = str_split($input);
array_splice($array, $i, 0, ' ');
$output[] = implode($array);
}
print_r($output);
Dont forget to check the codec. You might use mb_-prefix to use the multibyte-functions.

Converting a txt file to string, then to array and then printing each word of the array

I am trying to convert a text file into a string, then into an array and then finaly print each of the values (words) into separate 'a' holders.
The .txt file contains one line of text.
I have tried it through a for loop, like so:
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
for ($x = 1; $x >= 100; $x++){
print '<a id="word$x">'$words[$x]'</a>';
}
But that doesnt work. I am sure that I am just missing something basic, but I have tried and failed so many times, that I need others opinions and advice.
At first, don't forget about string concatenation: print '<a id="word'.$x.'">'.$words[$x].'</a>';
If you need more, than only 100 words use $x < count($words) in your for
You have to use <= instead of >=
for ($x = 1; $x <= 100; $x++){
print '<a id="word$x">'$words[$x]'</a>';
}
You can use sprinf, it's much easier to read.
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
for ($x = 1; $x >= 100; $x++){
echo sprintf('<a id="word%s">%s</a>', $word, $words[$x]);
}
But if you don't want to, you can simply concatenate the values.
echo '<a id="word' . $x . '">' . $words[$x] . '</a>';
It is a bad practice to use explicit for loops.
$lines = file_get_contents('test.txt', FILE_USE_INCLUDE_PATH);
$words = explode(" ", $lines);
$words = array_slice($words, 0, 100);
foreach ($words as $index => $word) {
print "<a id=\"word$x\">$word</a>";
}
Also, be aware array indexing starts with 0 not 1. If you do $x = 1 you will end up losing the first word!
If you want to print all words, just lose the $words = array_slice($words, 0, 100);. Read more about array_slice here.

php change the array value

I have an Array like this
$first = array("10.2+6","5.3+2.2");
I want to convert it like this
$second = array("10+10+6","5+5+5+2+2");
I also want to print out this such as way
10
10
6
5
5
5
2
2
How can I do this?
You can use this preg_replace_callback function:
$first = array("10.2+6", "5.3+2.2");
$second = preg_replace_callback('/\b(\d+)\.(\d+)\b/', function($m){
$_r=$m[1]; for($i=1; $i<$m[2]; $i++) $_r .= '+' . $m[1] ; return $_r; }, $first);
print_r($second);
Output:
Array
(
[0] => 10+10+6
[1] => 5+5+5+2+2
)
We use this regex /\b(\d+)\.(\d+)\b/ where we match digits before and after DOT separately and capture them in 2 captured groups. Then in callback function we loop through 2nd captured group and construct our output by appending + and 1st captured group.
Here's a solution using regular expressions and various functions. There are many ways to accomplish what you're asking, and this is just one of them. I'm sure this could even be improved upon, but here it is:
$first = array("10.2+5","5.3+2.2");
$second = array();
$pattern = '/(\d+)\.(\d)/';
foreach($first as $item){
$parts = explode('+',$item);
$str = '';
foreach($parts as $part){
if(strlen($str)>0) $str .= '+';
if(preg_match_all($pattern, $part, $matches)){
$str .= implode("+", array_fill(0,$matches[2][$i], $matches[1][$i]));
}else{
$str .= $part;
}
}
$second[] = $str;
}
print_r($second);
Output:
Array
(
[0] => 10+10+5
[1] => 5+5+5+2+2
)
<?php
$first = array("10.2+5","5.3+2");
foreach($first as $term)
{
$second="";
$a=explode("+", $term);
$b=explode(".", $a[0]);
$c=$b[0];
for ($i=0;$i<$b[1];$i++)
$second=$second.$c."+";
echo $second.$a[1]."+";
}
?>

Merging two words together letter by letter in php. How to make it work?

How to merge two words together letter by letter in php on the following way:
Input #1: Apricot
Input #2: Kiwi
Expected output: AKpirwiicot.
So that if one word's characters are more than the other, it simply writes it down until the end.
I tried it by this logic:
Input smthing
str_split()
array_merge()
But I failed. Any solutions appreciated.
$string1 and $string2 can be in any order.
$string1=str_split("Apricot");
$string2=str_split("Kiwi");
if(count($string2)>count($string1)){
$templ = $string1;
$string1 = $string2;
$string2 = $temp;
}
$result = "";
foreach($string1 as $key => $var){
{
$result.=$var;
if(isset($string2[$key])){
$result.$string2[$key];
}
}
echo $result;
Array_merge() also sticks one array on the end of the other so it wouldn't do what you are looking for I believe.
edit : ive adjusted to take into account no order, like #nikkis answer.
How about this:
def str_merge(a, b):
s = ''
k = min(len(a), len(b))
for i in range(k):
s += a[i] + b[i]
s += a[k:] + b[k:]
return s
In PHP:
function merge($a, $b)
{
$s = '';
$k = min(strlen($a), strlen($b));
for($i=0; $i<$k; $i++)
{
$s = $s . $a[$i] . $b[$i];
}
$s = $s . substr($a, $k) . substr($b, $k);
}
Please forgive my PHP, not my strongest language...

Efficient check for array items in a string

I have an array like:
arr = array("*" , "$" , "and" , "or" , "!" ,"/");
and another string like :
string = "this * is very beautiful but $ is more important in life.";
I'm looking the most efficient way with the lowest cost to find the member of the array in this string. Also I need to have an array in result that can show which members exist in the string.
The easiest way is using a for loop but I believe there should be more efficient ways to do this in PHP.
$arr=array("*" , "$" , "#" , "!");
$r = '~[' . preg_quote(implode('', $arr)) . ']~';
$str = "this * is very beautiful but $ is more important in life.";
preg_match_all($r, $str, $matches);
echo 'The following chars were found: ' . implode(', ', $matches[0]);
If you are looking for the most efficient way, the result of the following code is:
preg:1.03257489204
array_intersect:2.62625193596
strpos:0.814728021622
It looks like looping the array and matching using strpos is the most efficient way.
$arr=array("*" , "$" , "#" , "!");
$string="this * is very beautiful but $ is more important in life.";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$r = '~[' . preg_quote(implode('', $arr)) . ']~';
$str = "this * is very beautiful but $ is more important in life.";
preg_match_all($r, $str, $matches);
}
echo "preg:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$str = str_split($string);
$out = array_intersect($arr, $str);
}
echo "array_intersect:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$res = array();
foreach($arr as $a){
if(strpos($string, $a) !== false){
$res[] = $a;
}
}
}
echo "strpos:". (microtime(true)-$time)."\n";
You can use array_insersect
$string = "this * is very beautiful but $ is more important in life.";
$arr=array("*" , "$" , "#" , "!");
$str = str_split($string);
$out = array_intersect($arr, $str);
print_r($out);
This code will produce the following output
Array ( [0] => * [1] => $ )

Categories