So I wrote the following code to show the words after the fourth full stop / period in a sentence.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i];
}
The algorithm is working and it is showing me the rest of the sentence after the fourth "." full stop / period.... My problem is that the output is not showing the full stops in the sentence therefore it is showing me just text without the proper punctuation "." .... Can someone please help me out on how to fix the code to display also the full stops / periods ??
Thanks a lot
you could try this...
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i].".";
}
notice the added period at the end of the echo command // .".";
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i].".";
}
Instead of splitting the input string and then iterating over it, you can find the nth position of the separator (.) in the string by using strpos() function by changing the offset parameter.
Then, it is just the matter of printing the sub-string from the position we just determined.
<?php
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$pos = 0;
//find the position of 4th occurrence of dot
for($i = 0; $i < $limit; $i++) {
$pos = strpos($text, '.', $pos) + 1;
}
print substr($text, $pos);
If desired output is "seperated.with.full.stops.", then you can use:
<?php
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
$minText = array_slice($minText, $limit);
echo implode('.', $minText) . '.';
If you want to break it up on the periods between words, but keep the one at the end as actual punctuation, you may want to use preg_replace() to convert the periods to another character and then explode it.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
//replace periods if they are follwed by a alphanumeric character
$toSplit = preg_replace('/\.(?=\w)/', '#', $text);
$minText = explode("#", $toSplit);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i] . "<br/>";
}
Which Yields
seperated
with
full
stops.
Of course, if you just simply want to print all the full stops, then add them in after you echo the term.
echo $minText[$i] . ".";
Related
I'd like the code to output index 6 since d is the starting point in terms of the longest identical consecutive portion in the string.
Not sure what I'm doing wrong here but it's currently returning 3 instead. Seems like I'm going in the right direction but something is missing but I can't pinpoint what.
Any feedback is appreciated! :)
$str = "abbcccddddcccbba";
$array = preg_split('/(.)(?!\1|$)\K/', $str);
$lengths = array_map('strlen', $array);
$maxLength = max($lengths);
$ans = array_search($maxLength, $lengths); // returns 3 but need it to return 6
echo $ans;
$lengths = array_map('strlen', $array);
Above line has only lengths of adjacent similar characters. array_search on max of those lengths will only yield the index where the maximum length is stored. It is totally unrelated with getting the index 6 of your string. If you still wish to get it, you will have to array_sum till that index to get the start index in the actual string.
Snippet:
<?php
$str = "abbcccddddcccbba";
$array = preg_split('/(.)(?!\1|$)\K/', $str);
$lengths = array_map('strlen', $array);
$maxLength = max($lengths);
array_splice($lengths,array_search($maxLength, $lengths));
$ans = array_sum($lengths);
echo $ans;
Online Demo
Alternate Solution:
I would write a simple for loop that uses 2 pointers to keep track of start index of similar characters and record the frequency and start index whenever it is greater than max frequency.
Snippet:
<?php
$str = "abbcccddddcccbba";
$len = strlen($str);
$maxF = 1;
$maxIdx = $startIdx = 0;
for($i = 1; $i < $len; ++$i){
if($str[ $i ] != $str[ $i - 1] || $i === $len - 1){
if($str[ $i ] === $str[ $i - 1] && $i === $len - 1) $i++;
if($maxF < $i - $startIdx){
$maxF = $i - $startIdx;
$maxIdx = $startIdx;
}
$startIdx = $i;
}
}
echo $maxIdx;
Online Demo
I had a PHP string which contains English words. I want to extract all the possible words from the string, not by explode() by space as I have only a word. I mean extraction of words from a word.
Example: With the word "stackoverflow", I need to extract stack, over, flow, overflow all of them.
I am using pspell_check() for spell checking. I am currently getting the following combination.
--> sta
--> stac
--> stack
and so on.
So I found the only the words matching stack but I want to find the following words. Notice that I don't want the final word as I've already.
--> stack
--> over
--> flow
My Code:
$myword = "stackoverflow";
$word_length = strlen($myword);
$myword_prediction = $myword[0].$myword[1];
//(initial condition as words detection starts after 3rd index)
for ($i=2; $i<$word_length; $i++) {
$myword_prediction .= $myword[$i];
if (pspell_check(pspell_new("en"), $myword_prediction))
{
$array[] = $myword_prediction;
}
}
var_dump($array);
How about if you have an outer loop like this. The first time through you start at the first character of $myword. The second time through you start at the second character, and so on.
$myword = "stackoverflow";
$word_length = strlen($myword);
$startLetter = 0;
while($startLetter < $word_length-2 ){
$myword_prediction = $myword[$startLetter] . $myword[$startLetter +1];
for ($i=$startLetter; $i<$word_length; $i++) {
$myword_prediction .= $myword[$i];
if (pspell_check(pspell_new("en"), $myword_prediction)) {
$array[] = $myword_prediction;
}
}
$startLetter ++;
}
Well, you would need to get all substrings, and check each one:
function get_all_substrings($input){
$subs = array();
$length = strlen($input);
for($i=0; $i<$length; $i++){
for($j=$i; $j<$length; $j++){
$subs[] = substr($input, $i, $j);
}
}
return array_unique($subs);
}
$substrings = get_all_substrings("stackoverflow");
$pspell_link = pspell_new("en");
$words = array_filter($substrings, function($word) use ($pspell_link) {
return pspell_check($pspell_link, $word);
});
var_dump($words);
I'm trying to reorder the BBCodes but I failed
so
[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶ ̶-̶ ̶w̶r̶o̶n̶g̶ ̶o̶r̶d̶e̶r̶ ̶ ̶
I̶ ̶w̶a̶n̶t̶ ̶i̶t̶ ̶t̶o̶ ̶b̶e̶:̶ ̶
̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶u̶]̶[̶/̶i̶]̶[̶/̶b̶]̶ ̶-̶ ̶r̶i̶g̶h̶t̶ ̶o̶r̶d̶e̶r̶
PIC:
I tried with
<?php
$string = '[b][i][u]foo[/b][/u][/i]';
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is');
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]');
echo preg_replace($search, $replace, $string);
?>
OUTPUT: [b][i][u]foo[/b][/u][/i]
any suggestions ? thanks!
phew, spent awhile thinking of the logic to do this. (feel free to put it in a function)
this only works for the scenario given. Like other users have commented it's impossible. You shouldn't be doing this. Or even on server side. I'd use a client side parser just to throw a syntax error.
supports [b]a[i]b[u]foo[/b]baa[/u]too[/i]
and bbcode with custom values [url=test][i][u]foo[/url][/u][/i]
Will break with
[b] bold [/b][u] underline[/u]
And [b] bold [u][/b] underline[/u]
//input string to be reorganized
$string = '[url=test][i][u]foo[/url][/u][/i]';
echo $string . "<br />";
//search for all opentags (including ones with values
$tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/";
preg_match_all($tagsearch, $string, $tags);
//search for all close tags to store them for later
$closetagsearch = "/(\[\/([A-Za-z]+)\])/is";
preg_match_all($closetagsearch, $string, $closetags);
//flip the open tags for reverse parsing (index one is just letters)
$tags[1] = array_reverse($tags[1]);
//create temp var to store new ordered string
$temp = "";
//this is the last known position in the original string after a match
$last = 0;
//iterate through each char of the input string
for ($i = 0, $len = strlen($string); $i < $len; $i++) {
//if we run out of tags to replace/find stop looping
if (empty($tags[1]) || empty($closetags[1]))
continue;
//this is the part of the string that has no matches
$good = substr($string, $last, $i - $last);
//next closing tag to search for
$next = $closetags[1][0];
//how many chars ahead to compare against
$scope = substr($string, $i, strlen($next));
//if we have a match
if ($scope === "$next") {
//add to the temp variable with a modified
//version of an open tag letter to become a close tag
$temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0);
//remove the first key/value in both arrays
array_shift($tags[1]);
array_shift($closetags[1]);
//update the last known unmatched char
$last += strlen($good . $scope);
}
}
echo $temp;
Please also note: it might be the users intention to nest the tags out of order :X
I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.
I want it to be able to go through all the possible combinations for the given string, for example:
go one-by-one
then combo i.e.. 2 at a time, then three at a time, till you get length at a time
then start in combo split, i.e.. first and last, then first and second to last
then first and last two, fist and second/third last
So for the characters "abcd" it would return:
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
etc.......... so on and so forth till there are no other combinations
Any ideas, or has anyone seen a function somewhere I could modify for this purpose?
loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character
$str = 'abcd';
$len = strlen($str);
for($i = 0; $i < 1 << $len; $i++) {
$p = '';
for($j = 0; $j < $len; $j++)
$p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
echo $p, "\n";
}
There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.
<?php
$input = 'abcd';
$len = strlen($input);
$stop = pow(2, $len);
for ($i = 0; $i < $stop; ++$i)
{
for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
{
echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
}
echo "\n";
}
How about this?
<?php
function permutations($str, $n = 0, $prefix = "") {
if ($n == strlen($str)) {
echo "$prefix\n";
return;
}
permutations($str, $n + 1, $prefix . $str[$n]);
permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}
permutations("abcd");
?>
I need to find substrings of a given string but the substrings must be a word in the English language.
I.E. Given string = every, then substrings will be "ever", "very" and etc.
Thanks for the help.
You will need two things. First, you have to find all possible substrings. Then you will need a list with all English words (there are many free compilations).
This is a possible implementation:
$result = array();
$len = strlen($string)
for ($i = 0; $i < $len; $i++) {
for ($j = 1; $j <= $len - $i; $j++) {
$substring = substr( $string , $i , $j );
if ( is_an_english_word( $substring ) )
$result[] = $substring;
}
}