How can I split a string into three word chunks? - php

I need to split a string in every three words using PHP
"This is an example of what I need."
The output would be:
This is an
is an example
an example of
example of what
of what I
what I need
I have this example with Java
String myString = "This is an example of what I need.";
String[] words = myString.split("\\s+");
for (int i = 0; i < words.length; i++) {
String threeWords;
if (i == words.length - 1)
threeWords = words[i];
else if(i == words.length - 2)
threeWords = words[i] + " " + words[i + 1];
else
threeWords = words[i] + " " + words[i + 1] + " " + words[i + 2];
System.out.println(threeWords);
}

Solution that use explode, array_slice and implode.
$example = 'This is an example of what I need.';
$arr = explode(" ",$example);
foreach($arr as $key => $word){
//if($key == 0) continue;
$subArr = array_slice($arr,$key,3);
if(count($subArr) < 3) break;
echo implode(" ",$subArr)."<br>\n";
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need.
If you want to suppress the first output with This, remove the comment in the line
//if($key == 0) continue;
If the example can have less than 3 words and these should be output then the line with the break must be as follows:
if(count($subArr) < 3 AND $key != 0) break;
For strings that are not only separated by single spaces, preg_split is recommended. Example:
$example = "This is an example of what I need.
Sentence,containing a comma and Raphaël.";
$arr = preg_split('/[ .,;\r\n\t]+/u', $example, 0, PREG_SPLIT_NO_EMPTY);
foreach($arr as $key => $word){
$subArr = array_slice($arr,$key,3);
if(count($subArr) < 3) break;
echo implode(" ",$subArr)."<br>\n";
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need
I need Sentence
need Sentence containing
Sentence containing a
containing a comma
a comma and
comma and Raphaël

To include only words (notice the fullstop is removed from the last trigram), use str_word_count() to form the array of strings.
Then you need to loop while there are three elements to print.
Code: (Demo)
$example = 'This is an example of what I need.';
$words = str_word_count($example, 1);
for ($x = 0; isset($words[$x + 2]); ++$x) {
printf("%s %s %s\n", $words[$x], $words[$x + 1], $words[$x + 2]);
}
Output:
This is an
is an example
an example of
example of what
of what I
what I need
If you don't like printf(), you could echo implode(' ', [the three elements]).
If you want to print a single string of words when there are less than 3 total words in the string, then you could use a post-test loop. Demo
And then, of course, if we going to stumble down the rocky road of "what is a word", then an ironclad definition of "what is a word" will need to be defined and then a regex (potentially with multibyte support) will need to be suitably crafted. Basic Demo

Related

how to get first two word from a sentence using php for loop

I am trying to get first two word from a sentence using php
$inp_val= "this is our country";
output will be : this is
// this input value has different string as Like: this, this is our, this name is mine
// i need to get only first two word or if anyone wrote only one word then i got same word but if any one wrote two or more word then it will collect only first two word..
I am trying with below code but it won't work properly..
$words = explode(' ', $inp_val);
$shop_name = "";
if (str_word_count($words) == 1) {
$shop_name .= mb_substr($words[0], 0, 1);
} else {
for ($i = 0; $i < 2; $i++) {
$w = $words[$i];
$shop_name .= mb_substr($w, 0, 1);
}
}
After exploding the input value by space (as you have done), you can use array_slice to extract the 2 first elements, then use the implode to concat the 2 elements as a string.
$inp_val = "this is our country";
$shop_name = implode(" ", array_slice(explode(' ', $inp_val), 0, 2));
echo $shop_name;
//OUTPUT: this is
This method that uses array_slice work well for one or more words

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...

Search Inputted Text For Bad Words Defined In Array in PHP

I want to create a little script which will take in the user's inputted text and then search the text for bad words. The bad words are defined in an array. As far as I get it, I should have the following process:
Get input from the user - this part is easy, use the $_POST array
Convert the inputted string into an array - make use of the explode() function
Create 2 for loops, 1 outer for loop and 1 inner for loop. Inside the inner for loop, create an if statement that will check for bad words.
I want each time a bad word is found, it will increment the variable which will count the total number of bad words.
I manage to code all this, but my counter isn't working as it should, it gives me 0.
Here is the code below:
<?php
$badWordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = strtolower($inputedText);
$inputedText_ToProcess = explode(" ", $inputedText_ToProcess);
$outerLoop = sizeof($inputedText_ToProcess);
$innerLoop = sizeof($badWords);
for ($a = 0; $a < $outerLoop ; $a++)
{
for ($b = 0; $b < $innerLoop; $b++)
{
if ($badWords[$b] == $inputedText_ToProcess[$a])
{
$badwordCounter = $badWordCounter + 1;
}
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: $badWordCounter</p>";
echo "The entered text string is: $inputedText";
?>
Watch the case of your variables:
$bad**w**ordCounter = $badWordCounter + 1;
btw the nested loops are over-complicated, a cleaner example:
<?php
$_POST['inputText'] = 'come on you ass hole!'; // hardcoded for testing
$badwordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = strtolower($inputedText);
$inputedText_ToProcess = explode(" ", $inputedText_ToProcess);
// Iterate through each word
foreach ($inputedText_ToProcess as $word) {
// If that word exists in the badWords array
if (in_array($word, $badWords)) {
$badwordCounter++;
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: $badwordCounter</p>";
echo "The entered text string is: $inputedText";
You can use foreach for going through the whole array. Easier than a 'for' loop. Also, there's a function called in_array, which checks if the string given as the first parameter is in the array given as the second parameter. So this one should work:
<?php
$badWordCounter = 0;
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
$inputedText = $_POST['inputText'];
$inputedText_ToProcess = explode(" ", $inputedText);
foreach ($inputedText_ToProcess as $value) {
if (in_array(strtolower($value), $badWords)) {
$badWordCounter++;
}
}
echo "<p>The Total Number of Bad Words Detected In The Text: " . $badWordCounter . "</p>";
echo "The entered text string is: " . $inputedText;
?>
You forgot a capital on Word in your variable badWordCounter when incrementing it.
It should read:
$badWordCounter = $badWordCounter + 1;
Instead of:
$badwordCounter = $badWordCounter + 1;
You could have also used $badWordCounter++;
Since everyone is posting additional code that doesn't work, I thought I would offer a solution that is simpler and works with punctuation:
$badWords = array("bitch", "hoe", "slut", "motherfucker", "fuck", "ass", "cunt");
preg_match_all("/".implode('|', $badWords)."/i", $_POST['inputText'], $badWordCounter);
echo '<p>The Total Number of Bad Words Detected In The Text: '.count($badWordCounter[0]).'</p>';
echo 'The entered text string is: '.$_POST['inputText'];

Add +1 to a string obtained from another site

I have a string I get from a website.
A portion of the string is "X2" I want to add +1 to 2.
The entire string I get is:
20120815_00_X2
What I want is to add the "X2" +1 until "20120815_00_X13"
You can do :
$string = '20120815_00_X2';
$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);
$incremented = $concat . ($num + 1);
echo $incremented;
For more informations about substr() see => documentation
You want to find the number at the end of your string and capture it, test for a maximum value of 12 and add one if that's the case, so your pattern would look something like:
/(\d+)$/ // get all digits at the end
and the whole expression:
$new = preg_replace('/(\d+)$/e', "($1 < 13) ? ($1 + 1) : $1", $original);
I have used the e modifier so that the replacement expression will be evaluated as php code.
See the working example at CodePad.
This solution works (no matter what the number after X is):
function myCustomAdd($string)
{
$original = $string;
$new = explode('_',$original);
$a = end($new);
$b = preg_replace("/[^0-9,.]/", "", $a);
$c = $b + 1;
$letters = preg_replace("/[^a-zA-Z,.]/", '', $a);
$d = $new[0].'_'.$new[1].'_'.$letters.$c;
return $d;
}
var_dump(myCustomAdd("20120815_00_X13"));
Output:
string(15) "20120815_00_X14"

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);

Categories