This question already has answers here:
php - explode string at . but ignore decimal eg 2.9
(2 answers)
Closed 9 years ago.
I have a long string of text. I want to store it in an array by 2 sentences per element. I think it should be done by exploding the text around dot+space; however, there are elements like 'Mr.' which I don't know how to exclude from the explode function.
I also don't know how to adjust it to explode the text by 2 sentences, not by 1.
maybe something like:
$min_sentence_length = 100;
$ignore_words = array('mr.','ms.');
$text = "some texing alsie urj skdkd. and siks ekka lls. lorem ipsum some.";
$parts = explode(" ", $text);
$sentences = array();
$cur_sentence = "";
foreach($parts as $part) {
// Check sentence min length and is there period
if (strlen($cur_sentence) > $min_sentence_length &&
substr($part,-1) == "." && !in_array($part, $ignore_words)) {
$sentences[] = $cur_sentence;
$cur_sentence = "";
}
$cur_sentence .= $part . " ";
}
if (strlen($cur_sentence) > 0)
$sentences[] = $cur_sentence;
The comments on your question link to answers that use preg_split() instead of explode() to provide more accurate description of how and when to split the input. That might work for you. Another approach would be to split your input on every occurrence of ". " into a temporary array, then loop through that array, piecing it back together however you like. e.g.
$tempArray = explode('. ', $input);
$outputArray = array();
$outputElement = '';
$sentenceCount = 0;
foreach($tempArray as $part){
$outputElement .= $part . '. ';
//put other exceptions here, not just "Mr."
if ($part != 'Mr'){
$sentenceCount++;
}
if ($senteceCount == 2){
$outputArray[] = $outputElement;
$outputElement = '';
$sentenceCount = 0;
}
}
Related
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
I'm using explode() php function to divide the sentence and turn it into array the user had filled in the input field on different page. From that sentence I need to find if there is that word and if it is in it add <b></b> around of that word. I've tried:
$wordsentence = explode(' ', $wordsentence);
$place == '0';
foreach ($wordsentence as $ws) {
if ($ws == $word) {
$word = '<b>'.$word.'</b>';
$save = $place;
}
$place++;
}
but there might be more than one word in the same sentence. Is there any way to mark multiple words?
You initial setup:
$wordSentence = "This is a sentence, made up of words";
$wordTest = "made";
$wordsArr = explode(' ', $wordSentence);
I swapped out the foreach loop for a standard for loop, this way we don't need to initialize a separate index variable and keep track of it.
for ($i = 0; $i < count($wordsArr); $i++) {
if ($wordsArr[$i] == $wordTest) {
$boldWord = '<b>' . $wordTest . '</b>';
//take your wordsArray, at the current index,
//swap out the old version with the bold version
array_splice($wordsArr, $i, 1, $boldWord);
}
}
And to complete our test:
$boldedSentence = implode(' ', $wordsArr);
echo $boldedSentence . "\n";
Output:
> This is a sentence, <b>made</b> up of words
Lets say I have a text document that cannot be changed in any way and needs to be left as is.
Example of what the text document is likely formatted to be:
1. What is soup commonly paired with?
2.
3.
4. Alcohol
5. Water
6. Bread
7. Vegtables
8.
9.
10.
Note:
The numbers are not included, but they are used to represent the small spaces in between the words that are always there.
There is not always a question mark with the question
Note 2:
The question may be on 2 lines sometimes and may look like this below
0. What is soup
1. commonly paired with?
2.
3.
4. Alcohol
5. Water
6. Bread
7. Vegtables
8.
9.
10.
Other:
So how exactly do I seperate them, for example into an array?
So like $questions[] and $answers[]
The main problem is that I have nothing to link the questions and answers to:
I can't guess the exact line they are on
And the question doesn't always have a question mark
So there is nothing I can really link it to?
Assuming you have already read the text from the document into a variable $text, you can separate the question and answers by splitting on the first blank line in the text.
$qAndAs = preg_split('/\n\s*\n/', $text, 2, PREG_SPLIT_NO_EMPTY);
The split pattern is a line break (\n), zero or more whitespaces (\s*), and another line break.
That should give you an two-element array, where [0] is the question and [1] is the answers.
If it doesn't, then something went wrong.
if (count($qAndAs) !== 2) {
// The text from the document didn't fit the expected pattern.
// Decide how to handle that. Maybe throw an exception.
}
After you have separated them, you can remove any new lines from the question
$question = str_replace(["\r", "\n"], ' ', trim($qAndAs[0]));
and split your answers into another array.
$answers = preg_split('/\s*\n\s*/', $qAndAs[1], -1, PREG_SPLIT_NO_EMPTY);
Both solutions accept multiple questions / answers in a single file.
Solution 1 (similar to the other one in this thread):
$questions = array();
$answers = array();
//Split text into questions and answers blocks (2 line breaks or more from each other)
$text = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
foreach ($text as $key => $value)
{
//0, 2, 4, ... are questions, 1, 3, 5, ... are answers
if ($key % 2)
{
$answers[] = explode("\n", $value);
}
else
{
$questions[] = str_replace("\n", '', $value);
}
}
Solution 2 (ugly line by line reading from a file):
//Open the file
$f = fopen("test.txt","r");
//Initialize arrays of all questions and all answers
$all_questions = array();
$all_answers = array();
$is_question = true;
$last = ''; //contains a previous line
//Iterate over lines
while (true)
{
//Get line
$line = fgets($f);
//Check if end of file
$end = ($line === false);
//Trim current line
$line = trim($line);
if ($line != '')
{
//If the previous line was empty, then reset current question and answers
if ($last == '')
{
$question = array();
$answers = array();
}
//Add line of question or answer
if ($is_question)
{
$question[] = $line;
}
else
{
$answers[] = $line;
}
}
else
{
//If the previous line wasn't empty, or we reached the end of file, then save question / answers, and toggle $is_question
if ($last != '' OR $end)
{
if ($is_question)
{
$all_questions[] = implode(' ', $question); //implode to merge multiline question
$is_question = false;
}
else
{
$all_answers[] = $answers;
$is_question = true;
}
}
}
//Break if end of file
if ($end)
{
break;
}
$last = $line;
}
fclose($f);
This question already has answers here:
How to split a long string without breaking words?
(4 answers)
Closed 7 years ago.
I created a variable which stores a very long string, and I want to print this variable in multiple lines.
$test ="This is some example text , I want to print this variable in 3 lines";
The output of the above $test would be
This is some example text,
I want to print this
variabale in 3 lines
Note: I want a new line after each 15 characters or each line have equal characters. I don't want to add break tag or any other tag during variable assignment.
CODEPAD
<?php
$str= 'This is some example text , I want to print this variable in 3 lines, also.';
$x = '12';
$array = explode( "\n", wordwrap( $str, $x));
var_dump($array);
?>
or use
$array = wordwrap( $str, $x, "\n");
Try this
<?php
$test ="This is some example text , I want to print this variable in 3 lines";
$array = str_split($test, 10);
echo implode("<br>",$array);
Based on this link
PHP: split a long string without breaking words
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$arrayWords = explode(' ', $longString);
// Max size of each line
$maxLineLength = 18;
// Auxiliar counters, foreach will use them
$currentLength = 0;
$index = 0;
foreach($arrayWords as $word)
{
// +1 because the word will receive back the space in the end that it loses in explode()
$wordLength = strlen($word) + 1;
if( ( $currentLength + $wordLength ) <= $maxLineLength )
{
$arrayOutput[$index] .= $word . ' ';
$currentLength += $wordLength;
}
else
{
$index += 1;
$currentLength = $wordLength;
$arrayOutput[$index] = $word;
}
}
The easiest solution is to use wordwrap(), and explode() on the new line, like so:
$array = explode( "\n", wordwrap( $str, $x));
Where $x is a number of characters to wrap the string on.
Copied from here last comment
Try This
<?php
$test ="This is some example text , I want to print this variable in 3 lines";
$explode=explode(" ",$test);
$String='';
$newString='';
$maxCharacterCount=23;
foreach ($explode as $key => $value) {
$strlen=strlen($String);
if($strlen<=$maxCharacterCount){
$String.=' '.$value;
}else{
$newString.=$String.' '.$value.'<br>';
$String='';
}
}
$finalString= $newString.$String;
echo $finalString;
?>
OK now all is working. You just pass $string and #maxlenght in characters number and function returns table with cutted string.
don`t cut words,
don`t ever exeed maxLenght,
Only one thing to rember is that u need to care for comma usage i.e: "word, word".
$test ="This is some example text, I want to print this variable in 3 lines dasdas das asd asd asd asd asd ad ad";
function breakString($string, $maxLenght) {
//preparing string, getting lenght, max parts number and so on
$string = trim($string, ' ');
$stringLenght = strlen($string);
$parts = ($stringLenght / $maxLenght );
$finalPatrsNumber = ceil($parts);
$arrayString = explode(' ', $string);
//defining variables used to store data into a foreach loop
$partString ='';
$new = array();
$arrayNew = array();
/**
* go througt every word and glue it to a $partstring
*
* check $partstring lenght if it exceded $maxLenght
* then delete last word and pass it again to $partstring
* and create now array value
*/
foreach($arrayString as $word){
$partString.=$word.' ';
while( strlen( $partString ) > $maxLenght) {
$partString = trim($partString, ' ');
$new = explode(' ', $partString);
$partString = '';
$partString.= end($new).' ';
array_pop($new);
//var_dump($new);
if( strlen(implode( $new, ' ' )) < $maxLenght){
$value = implode( $new, ' ' );
$arrayNew[] = $value;
}
}
}
// /**
// * psuh last part of the string into array
// */
$string2 = implode(' ', $arrayNew);
$string2 = trim($string2, ' ');
$string2lenght = strlen($string2);
$newPart = substr($string, $string2lenght);
$arrayNew[] = $newPart;
/**
* return array with broken $parts of $string
* $party max lenght is < $maxlenght
* and breaks are only after words
*/
return $arrayNew;
}
/**
* sample usage
* #param string $string
* #param int $maxLenght Description
*/
foreach( breakString($test, 30) as $line){
echo $line."<br />";
}
displays:
This is some example text, I
want to print this variable
in 3 lines dasdas das asd asd
asd asd asd ad ad
btw. u can easly add here some rules like:
no single char in last row or don`t break on certain words and so on;
I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;