Group or list words by first 2 letters - php

I'd like to list/group words by the first two letters but I can't get my head around it. I guess I can I can do a substr() and check against while looping but I'm not sure if this is the way to do it.
Something like:
if (substr($word, 0, 2) == 'aa') {
echo $word;
}
What I'm trying to achieve:
Words get sorted first by their starting letter, e.g. A, B, C etc. On the A page you have the words sorted by the first 2 letters, e.g. aa, ab, ac etc.
An example for this is http://www.urbandictionary.com/browse.php?word=aa. They do exactly what I'm after.
Help/thoughts appreciated!

If you have a bunch of words, put them grouped together in an array.
for example:
<?php
$myWords = array ("hello", "hell", "ape", "word", "appel");
$myGroupedArr = array();
foreach ($myWords as $oneWord){
$firstTwo = substr($oneWord,0,2);
$myGroupedArr[$firstTwo][] = $oneWord;
}
echo "<pre>";
print_r($myGroupedArr);
echo "</pre>";
?>

I would sort not only by the first letter, but by the whole word, or at least by the first two letters.
Then, you can indeed use substr to get the first two letters of the first word. You can then enter the loop, and check the first two letters of the word in the loop, with the two letters you got before.
If they differ, you know you got a new group. You can echo a group header and store the new to letters to compare with in the following iterations.
// Words in a sorted array.
$words = array( ...... );
asort($words);
$currentGroup = '';
foreach ($words as $word)
{
$newGroup = substr($word, 0, 2);
if ($newGroup !== $currentGroup)
{
// A new group is starting.
echo "=== $newGroup ===<br/>";
$currentGroup = $newGroup;
}
echo $word . '<br/>';
}

Related

Trying to get lowest value before comma from string using explode

I am new to php but learning fast. I am trying to extract the lowest price from a string of values like -
"12/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81"
I need to get the value just before each comma and then get the lowest of these values. I know I can use min() if I get these values in a string. For the above example I need 275.81 (lowest).
Please see my code below. I am trying to explode the values and then put in a string. I dont think this is the best way by far and not having any luck. is there a better/cleaner way to do this?
$dates = explode(',', $resultx);
foreach($dates as $datew) {
$dater = explode(':', $datew);
echo $dater[2]. ",";
}
You can use regular expressions to extract the values, and then use min() to get the minimum value
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$pattern = '/(?:[^\:]+)\:(?:[^\:]+)\:(\d+\.\d+)\,*/';
if (preg_match_all($pattern, $input, $matches)) {
$minimumValue = min($matches[1]);
echo "minimum is: " . $minimumValue;
}
Here is a working example on 3v4l.org
In the pattern (?:[^\:]+) - equals any symbol, except the colon :
Section (\d+\.\d+) says that we need to capture the sequence containing two numbers with a dot . between them.
We look for two sections with any symbols, except :, and then capturing the third sections containing numbers, and everything ends with an optional comma ,
P.S. you could still get the result with your current approach
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$minimumValue = null;
$dates = explode(',', $input);
foreach($dates as $datew) {
$dater = explode(':', $datew);
$currentValue = floatval($dater[2]);
if (is_null($minimumValue) || $minimumValue > $currentValue) {
$minimumValue = $currentValue;
}
}
echo $minimumValue;
Here is a link to your approach on 3v4l.org

Extract n-character substring while ignoring spaces

I need to extract a substring (for instance 22 characters) but I need to ignore spaces when counting the number of characters. For example:
$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";
Let's say I need to get the substring that contains the 22 first characters but without counting the spaces. substr doesn't work:
echo substr($para, 0, 22); // => While still in high sc
But I need to get
// => While still in high school
How can I do this?
^(?=((?>.*?\S){20}))
Try this.Grab the capture or group.See demo.
https://regex101.com/r/fM9lY3/42
This uses lookahead to capture 20 groups of any character and a non space character. Precisely,lookahead will search for groups ending with non space character.Because it is non greedy,it will search first such 20 groups.
you just need to provide a string and length you want to be extracted from that string and function will return that string of specified length(yes return string will have spaces in it, but spaces won't be included in string).
Here is snippet.
$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";
function getString($str, $length){
$newStr = "";
$counter = 0;
$r = array();
for($i=0; $i<strlen($str); $i++)
$r[$i] = $str[$i];
foreach($r as $char){
$newStr .= $char;
if($char != " "){
$counter += 1;
}
//return string if length reached.
if($counter == $length){
return $newStr;
}
}
return $newStr;
}
echo getString($para, 20);
//output: While still in high scho
echo getString($para, 22);
//output: While still in high school
First, use str_replace() to create a string $parawithoutspaces that consists of $para, without the spaces, like so:
$parawithoutspaces=str_replace(" ", "", $para);
Then, use substr() get the first 20 characters of $parawithoutspaces like so:
print substr($parawithoutspaces, 0, 20);
Or, combining the two steps into one and eliminating the need for the intermediate variable $parawithoutspaces:
print substr(str_replace(" ", "", $para),0,20);
You can try this, it is my code, $result is final string you want :
$arr1 = substr( $string,0,20);
$arr1 = explode(" ",$arr1);
array_pop($arr1);
$result = implode(" ",$arr1);

Trying to spit sentence into array with words

I am trying to split a sentence into an array with words, one word as each element, in PHP if there is more than one word in the sentence. If there is only one word in the sentence, then I just print that one word.
My issue is when I split the sentence into words delimited by a space and put the contents into an array. I do this all using explode. But when I run through the array that explode apparently makes, it says there is nothing in the array when I try to print each item.
Here is my code:
if(isset($_GET['check'])){
$input = trim($_GET['check']);
$sentence='';
if(stripos($input, ' ')!==false){
$sentence = explode(' ', $input);
foreach($sentence as $item){
echo $item;
}
}
else{
echo $input;
}
}
Why is echo $item; printing nothing? Why isn't there anything in the array $sentence?
Your code seems to be working fine. Make sure you're getting the variable. You can do a print_r($_GET);
You can also just do this:
<?php
$_GET['check'] = 'Hey how are you?';
if (isset($_GET['check'])) {
// each word is now an element in the array
$arr = explode(' ', trim($_GET['check']));
}
// piece each word back together with a space
echo implode(' ', $arr);
?>
It doesn't matter if it's a single word or multiple words.
UPDATE: If you really want to check if the user has entered one word or more than one word you can do this:
<?php
$_GET['check'] = 'Hey how are you?';
if (str_word_count($_GET['check']) > 1) {
echo 'More than one word';
} else {
echo 'Only one word';
}
?>
Check out str_word_count

Word counter: Doesn't seem to give the output I need (PHP)

here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);

Cannot read the first letter

I want to add a function to return whether the first letter is a capital or not from my last question.
Here's the code:
<?php
function isCapital($string) {
return $string = preg_match('/[A-Z]$/',$string{0});
}
$text = " Poetry. do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text); $save = array();
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save[] = $sentence. ".";
}
}
if( count( $save) > 0) {
foreach ($save as $nama){
if (isCapital($nama)){
print_r ($nama);
}
}
}
?>
The result should be...
Poetry can be divided into several genres, or categories.
...but it prints nothing. I need only the sentence that consists of more than 6 words and start with capital letter.
When you do the explode() function, you are leaving a space at the start of the string, which means that the leftmost character of $string will never be a capital letter--it will be a space. I would change the isCapital() function to the following:
function isCapital($string) {
return preg_match('/^\\s*[A-Z]/', $string) > 0;
}
You should be able to accomplish all of this through one regular expression, if you're so inclined:
preg_match_all('/((?=[A-Z])([^\s.!?]+\s+){5,}[^\s.!?]+[.!?])/', $string, $matches);
http://refiddle.com/2hz
Alternatively, remove the ! and ? from the character classes to only count . as a sentence delimiter.

Categories