Slice sentences in a text and storing them in variables - php

I have some text inside $content var, like this:
$content = $page_data->post_content;
I need to slice the content somehow and extract the sentences, inserting each one inside it's own var.
Something like this:
$sentence1 = 'first sentence of the text';
$sentence2 = 'second sentence of the text';
and so on...
How can I do this?
PS
I am thinking of something like this, but I need somekind of loop for each sentence:
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$sentence1 = $match[1];
$sentence2 = $match[2];
Ty:)

Do you need them in variables? Can't you use a array?
$sentence = explode(". ", $page_data->post_content);
EDIT:
If you need variables:
$allSentence = explode(". ", $page_data->post_content);
foreach($allSentence as $key => $val)
{
${"sentence". $key} = $val;
}

Assuming each sentence ends with full stop, you can use explode:
$content = $page_data->post_content;
$sentences = explode('.', $content);
Now your sentences can be accessed like:
echo $sentences[0]; // 1st sentence
echo $sentences[1]; // 2nd sentence
echo $sentences[2]; // 3rd sentence
// and so on
Note that you can count total sentences using count or sizeof:
echo count($sentences);
It is not a good idea to create a new variable for each sentence, imagine you might have long piece of text which would require to create that number of variables there by increasing memory usage. You can simply use array index $sentences[0], $sentences[1] and so on.

Assuming a sentence is delimited by terminating punctuation, optionally followed by a space, you can do the following to get the sentences in an array.
$sentences = preg_split('/[!?\.]\s?/', $content);
You may want to trim any additional spaces as well with
$sentences = array_map('trim', $sentences);
This way, $sentences[0] is the first, $sentences[1] is the second and so on. If you need to loop through them you can use foreach:
foreach($sentences as $sentence) {
// Do something with $sentence...
}

Don't use individually named variables like $sentence1, $sentence2 etc. Use an array.
$sentences = explode('.', $page_data->post_content);
This gives you an array of the "sentences" in the variable $page_data->post_content, where "sentences" really means sequences of characters between full stops. This logic will get tripped up wherever a full stop is used to mean something other than the end of a sentence (e.g. "Mr. Watson").
Edit: Of course, you can use more sophisticated logic to detect sentence boundaries, as you have suggested. You should still use an array, not create an unknown number of variables with numbers on the ends of their names.

Related

Php find and replace words in a text from database tables

I'm working on a project. It searches and replaces words from the database in a given text. In the database a have 10k words and replacements. So ı want to search for each word and replace this word's replacement word.
By the way, I'm using laravel. I need only replacement ideas.
I have tried some ways but it replaces only one word.
My database table structure like below;
id word replacement
1 test testing
etc
The text is coming from the input and after the replacement, I wanna show which words are replaced in a different bg color in the result page.
I tried below codes working fine but it only replaces one word.
$article = trim(strip_tags($request->article));
$clean = preg_split('/[\s]+/', $article);
$word_count = count($clean);
$words_from_database_for_search = Words::all();
foreach($words_from_database_for_search as $word){
$content = str_replace($word['word'],
"<span class=\"badge badge-success\">$word[replacement]
</span>",
$article);
}
$new_content = $content ;
$new_content_clean = preg_split('/[\s]+/', $new_content);
$new_content_word_count= count($new_content_clean);
Edit,
Im using preg_replace instead of str_replace. I get it worked but this time i wanna show how many words changed so i tried to find the number of changed words from the text after replacement. It counts wrong.
Example if there is 6 changes it show 3 or 4
It can be done via preg_replace_callback but i didnt use it before so i dont know how to figure out;
My working codes are below;
$old_article = trim(strip_tags($request->article));
$old_article_word_count = count($old_article );
$words_from_database_array= Words::all();
$article_will_replace = trim(strip_tags($request->article));
$count_the_replaced_words = 0;
foreach($words_from_database_array as $word){
$article_will_replace = preg_replace('/[^a-zA-
ZğüşıöçĞÜŞİÖÇ]\b'.$word['word'].'\b\s/u',
" <b>".$word['spin']."</b> ",
$article_will_replace );
$count_the_replaced_words = preg_match_all('/[^a-zA-
ZğüşıöçĞÜŞİÖÇ]\b'.strip_tags($word['spin']).'\b\s/u',$article_will_replace
);
if($count_the_replaced_words ){
$count_the_replaced_words ++;
}
}
As others have suggested in comments, it seems your value of $content is being overwritten on each run of the foreach loop, with older iterations being ignored. That's because the third argument of your str_replace is $article, the original, unmodified text. Only the last word, therefore, is showing up on the result.
The simplest way to fix this would be to declare $content before the foreach loop, and then make $content the third argument of the foreach loop so that it is continually replaced with a new word on each iteration, like so:
$content = $article;
foreach($words_from_database_for_search as $word){
$content = str_replace($word['word'],
"<span class=\"badge badge-success\">$word[replacement]</span>",
$content);
}
Im confused, don't you need the <?php ... ?> around the $word[replacement] ?
foreach($words_from_database_for_search as $word){
$content = str_replace($word['word'],
"<span class=\"badge badge-success\"><?PHP $word[replacement] ?>
</span>",
$article);
}
and then move this in to the for-loop and add a dot before the equal-sign:
$new_content .= $content ;

How to explode the string back from the second or third string delimiter?

How can I get the 800-555 from this 800-555-5555 with explode()?
Here is a good example:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
First chunk = $phoneChunks[0]; //800
Second chunk = $phoneChunks[1]; //555
Third Chunk chunk = $phoneChunks[2]; //5555
But how can I get the 800-555?
Okay, I see, here need more comment... So, this is only an example... In real I add a word (now $word) to string delimiter and my string is a full article... I want that, if this word second time published in the article, with str_word_count() will count, how many characters was in the text to the second (or third, if I want that) $word...
So I want that, I get the string from the second "hit" to back.
Okay, here is a more obvious example:
$text = oh my god, thank you the lot of downvotes, geniuses *.*
$explode = explode(",", $text);
$whatiwant = $explode?? // I WANT THE STRING FROM THE SECOND "," TO BACK
So I want that $whatiwant = oh my god, thank you the lot of downvotes
Implode, explode and array_slice.
I use array_slice because that makes the function more dynamic.
Now you can just set the $items to get the number of items you want.
If you set a negative value it counts backwards.
$delim = ",";
$items =2;
$text = "oh my god, thank you the lot of downvotes, geniuses *.*";
$whatiwant = implode($delim, array_slice(explode($delim, $text),0,$items));
Echo $whatiwant;
https://3v4l.org/KNSC4
You could also have an start variable to make the start position dynamic.
https://3v4l.org/XD0NV
Doing concatenation of already generated array's indexes is the simple way for you.
Sample Code
echo $phoneChunks[0]."-".$phoneChunks[1];
This is working for me:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
$first_chunk = $phoneChunks[0]; //800
$second_chunk = $phoneChunks[1]; //555
$third_chunk_chunk = $phoneChunks[2]; //5555
$portion_array = array($first_chunk, $second_chunk);
echo implode("-",$portion_array);
Output:
800-555

preg_replace suddenly stops making distinctions

Confounded. I've been using the below IF PREG_MATCH to distinguish between words which entire words and words which are parts of other words. It has suddenly ceased to function in this script, and any other script I use, which depend on this command.
The result is it finds parts of words, although you can see it is explicitly told to find only entire words.
$word = preg_replace("/[^a-zA-Z 0-9]+/", " ", $word);
if (preg_match('#\b'.$word.'\b#',$goodfile) && (trim($word) != "")) {
$fate = strpos($goodfile,$word);
print $word ." ";
print $fate ."</br>";
If you only want to read the first word of a line of a text file, like your title suggests, try another method:
// Get the file as an array, each element being a line
$lines = file("/path/to/file");
// Break up the first line by spaces
$words = explode(" ", $lines[0]);
// Get the first word
$firstWord = $words[0];
This would be faster and cleaner than explode and you won't be making any array
$first_word = stristr($lines, ' ', true);

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

How can we split a sentence

I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!

Categories