find position and frequency of words in sentences - php

I wanna find position and frequency of words in sentences.
for example :
You should eat two bananas before lunch and eat two before your dinner and then consume one banana.
so I will get the result :
You -> 1 -> position : 1
Should -> 1 -> position : 2
eat -> 2 -> position : 3, 9
etc.
For get the frequency I can use
array_count_values(str_word_count($str, 1))
but how to index to get the location?
thank you :)

Well, using your current function, you could just use a foreach loop, then gather them. Use explode and use their indices + 1. Example:
$str = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana.';
$count = array_count_values(str_word_count($str, 1));
$data = array();
// gather them first
foreach(explode(' ', $str) as $key => $value) {
$value = str_replace('.', '', $value);
$key = $key + 1;
$data[$value]['positions'][] = $key;
$data[$value]['count'] = $count[$value];
}
?>
<?php foreach($data as $word => $info): ?>
<p><?php echo "$word -> $info[count] -> Position: " . implode(', ', $info['positions']); ?></p>
<?php endforeach; ?>

$string = 'You should eat two bananas before lunch and eat two before your dinner and then consume one banana';
$array = explode ( ' ' , $string ) ;
$frequency = array_count_values ($array);
foreach ($frequency as $key => $value)
{
echo $key.' -> '.$value.' -> position : '.(array_search($key ,$array)+1).'</br>';
}

Related

Split strings in a flat array on the space between mixed-case words and all-caps words

I have this array
$arr2 = array(
"SUBTITLE",
"Test Your Might RUNTIME",
"1 hr 41 mins GENRE",
"Science-Fiction/Fantasy SYNOPSIS",
"his film adaptation of the wildly popular video game comes complete with dazzling special effects and plenty of martial arts action. LIGTHNING AND EFFECT"
);
And I would like to separate the words that are all upper case from the sentences that are lower. Like this.
$arr2 = array(
"SUBTITLE",
"Test Your Might",
"RUNTIME",
"1 hr 41 mins",
"GENRE",
"Science-Fiction/Fantasy",
"SYNOPSIS",
"his film adaptation of the wildly popular video game comes complete with dazzling special effects and plenty of martial arts action.",
"LIGHTNING AND EFFECT"
)
How would I do this? If there is a way to do this with regex, that would be preferred.
I used a separator to join the cases whenever there is a change. I don't know what other kind of data you could be passing so I left the separator as a variable to be changed easily.
$separator = '<br>';
foreach($arr2 as $index => $str) {
$str = explode(" ", $str);
$final_string = '';
$last_case = '';
foreach($str as $word) {
if ($word === strtoupper($word)) {
if ($last_case == 'lower') $final_string .= $separator.$word;
else $final_string .= $word . ' ';
$last_case = 'upper';
} else {
if ($last_case == 'upper') $final_string .= $separator.$word;
else $final_string .= $word . ' ';
$last_case = 'lower';
}
}
$arr2[$index] = explode($separator, trim($final_string));
}
$arr2 = array_reduce($arr2, 'array_merge', []);
print_r($arr2); // array ( 0 => 'SUBTITLE', 1 => 'Test Your Might ', 2 => 'RUNTIME', 3 => '1 hr 41 mins', 4 => 'GENRE', 5 => 'Science-Fiction/Fantasy', 6 => 'SYNOPSIS', 7 => 'his film adaptation of the wildly popular video game comes complete with dazzling special effects and plenty of martial arts action.', 8 => 'STARRING');
Here's what I would do:
<?php
$a = ['SUBTITLE', 'Test Your Might RUNTIME', '1 hr 41 mins GENRE', 'Science-Fiction/Fantasy SYNOPSIS', 'his film adaptation of the wildly popular video game comes complete with dazzling special effects and plenty of martial arts action. LIGTHNING AND EFFECT'];
foreach($a as $v){
if(preg_match('/(?:[A-Z]{2,}(?:\s+|$))+/', $v, $m)){
foreach($m as $s){
if($s === $v){
$r[] = $s;
}
else{
$r[] = str_replace($s, '', $v); $r[] = $s;
}
}
}
else{
$r[] = $v;
}
}
print_r($r);
?>
Please confirm it works as expected, but one way would be to do something like the following:
function splitter($jumbled) {
$lowercase = [];
foreach($jumbled as $element){
$exploded = explode(" ", $element);
foreach ($exploded as $word){
if ($word == strtoupper($word)){
$uppercase[] = $word;
} else {
$lowercase .= $word . ' ';
}
}
$output[] = $uppercase;
$output[] = rtrim($lowercase,' ');
}
return $output;
}
then just call the function with arr2: splitter($arr2)
(note: this returns the array as you requested, but it would be easier to use the array afterwords if you matched the corresponding values as an $uppercase => $lowercase key/value pair in the array being returned)
Use array_reduce() for a functional-style approach to return a result array with a different count than the input array.
Split on sequences of all-caps words, including their leading and trailing spaces. Capture the sequence of words so that only the outermost spaces are lost while splitting.
Merge all newly generated elements with the result array as you iterate so that you end up with a flat array.
Code: (Demo)
var_export(
array_reduce(
$array,
fn($result, $v) => array_merge(
$result,
preg_split(
'/ *\b([A-Z]+(?: [A-Z]+)*)\b */',
$v,
0,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
)
),
[]
)
);
Specifically tailored to your input which only has the all-caps words at the end of the string, you can use / (\[A-Z\]+(?: \[A-Z\]+)*)$/ with the same effect.

find same numbers in between -to- and group them

Here I want to find the same numbers in between - -
For example : Here (6-85-,7-85-,8-113-,) same numbers are 85. I want to find them and group them (add comma) like this
6,7
8
Another example :
2-1-,1-29-,4-57-,5-57-,6-85-,7-85-,8-113-,
2
1
4,5
6,7
8
Is there any way to do this in php? I have searched on here and other forums but never get any idea..
This is how I would do it:
$collect = array();
$s="2-1-,1-29-,4-57-,5-57-,6-85-,7-85-,8-113-,";
$a = explode(',', $s);
foreach($a as $v){
$m = explode('-',$v);
if( count($m) >= 2 ){
$collect[$m[1]][] = $m[0];
}
}
foreach($collect as $match){
echo implode(',', $match)."\n";
}

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]."+";
}
?>

Extract Words From Text That Have More Than 4 Charecters and Are A-Z

Hello I got this code from this this website and it works fine but want to be able to only show words with 4 charecters or more and A-Z no numbers. Any help would be very much appreciated thanks!
$myvalue = "no no2 yess";
$arr = explode(' ',trim($myvalue));
echo $arr[0];
$myvalue = "no no2 yess";
$arr = explode(' ',trim($myvalue));
Explode is cutting your string by delimeter ( ' ' ), and putting content into and array ( $arr ).
echo $arr[0]; // outputs 'no'
echo $arr[1]; // outputs 'no2'
echo $arr[2]; // outputs 'yess'
foreach($arr as $value){ // loop throught each element
//test if element is longer or equal to 4 and have only a-z A-Z.
if(strlen($value) >=4 & preg_match('/^[a-zA-Z]{4,}$/', $value)){
//return the matching words
echo $value;
}
}
Here you can putt them again into the array like $newArray[] = $value instead of echo $value, and throw them out with loop anywhere.

How remove the last comma in my string?

I've been trying to figgure out using substr, rtrim and it keeps removing all the commas. And if it doesn't nothing shows up. So I am basicly stuck and require some help.. Would've been apriciated.
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
I am guessing that you are trying to take an array of strings of space separated ids and flatten it into a comma separated list of the ids.
If that is correct you can do it as:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
output:
abc, def, ghi, jklm, nopq, rstu, vwxy
Change ltrim by rtrim:
ltrim — Strip whitespace (or other characters) from the beginning of a string
rtrim — Strip whitespace (or other characters) from the end of a string
<?php
$ids = Array ( 1,2,3,4 );
$final = '';
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$final .= $value . ', ';
}
}
echo rtrim($final, ', ') . '<br>';
echo substr($final, 0, -2) . '<br>'; //other solution
}
?>
If your array looks like;
[0] => 1,
[1] => 2,
[2] => 3,
...
The following should suffice (not the most optimal solution);
$string = ''; // Create a variable to store our future string.
$iterator = 0; // We will need to keep track of the current array item we are on.
if ( is_array( $ids ) )
{
$array_length = count( $ids ); // Store the value of the arrays length
foreach ( $ids as $id ) // Loop through the array
{
$string .= $id; // Concat the current item with our string
if ( $iterator >= $array_length ) // If our iterator variable is equal to or larger than the max value of our array then break the loop.
break;
$string .= ", "; // Append the comma after our current item.
$iterator++; // Increment our iterator variable
}
}
echo $string; // Outputs "1, 2, 3..."
Use trim() function.
Well, if you have a string like this
$str="foo, bar, foobar,";
use this code to remove the Last comma
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
output: foo, bar, foobar

Categories