I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?
Related
I have tried for hours to figure this out, to no avail. I have searched and searched, with a lot of results saying to use an array. I can not use an array as this has not been covered in my class yet. Here is what I am to do:
I am to use a for loop to examine the characters using index variable.
When a blank character is found, this indicated the end of the word.
I then need to extract the word from the string and increment the word count, thus printing the word count and extracted word, continuing til the end of the sentence.
Then printing the total word count.
What I am stuck on is extracting the word. Here is what I have so far, which could very well be wrong but I am at my wits end here, so any little bit of push in the right direction would be great.
(Remember, I can not use arrays.)
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = stripos($stringSentence, " ");
for ($i =0; $i<strlen($stringSentence);$i++)
{
$i. " ". $stringSentence{$i}."<br>";
}
if ($blankCharacter)
{
echo $wordcount++, " ";
echo substr($stringSentence,0,$blankCharacter);
}
Thanks for any help.
Have you considered just going through each individual letter to check for spaces and storing in a temporary buffer otherwise? One example:
$stringSentence = "The quick brown fox jumps over the lazy dog";
$buffer = '';
$count = 1;
$length = strlen($stringSentence);
for ($i = 0; $i < $length; $i++) {
if ($stringSentence{$i} !== ' ') {
$buffer .= $stringSentence{$i};
} else {
echo $count++ . ' ' . $buffer . ' ';
$buffer = '';
}
}
echo $count . ' ' . $buffer;
I'm not putting much explanation into my answer.. sort of a backwards approach of giving you the answer but it's up to you to understand how and why the above approach works.
Since this is home work I can't do it for you but you have an end bracket for one in the wrong place
Have a look at this sudo code and you should be in the right direction.
$blankCharacter = ' ';
for ($i =0; $i<strlen($stringSentence);$i++)
{
if (thisCharacter == $blankCharacter)
{
$wordcount++;
}
}
Arrays aren't that complicated! And a solution is very easy with it:
(Here I just explode() your string into an array. Then I simply loop through the array and print the output)
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$words = explode(" ", $stringSentence);
foreach($words as $k => $v)
echo "WordCount: " . ($k+1) . "| Word: $v<br>";
echo "Total WordCount: " . count($words);
?>
output:
WordCount: 1| Word: The
//...
WordCount: 9| Word: dog
Total WordCount: 9
If you want to read more about arrays see the manual: http://php.net/manual/en/language.types.array.php
EDIT:
If you can't use arrays, just use this:
Here I just loop through all characters of the sentence to check if it is either a space OR the end of the string. If the condition is true I print the word count + the substr from the last space until the current one. Then I also increment the word count with 1. At the end I simply print the total word count (note that I subtracted 1, because the last word will also add 1 to the count which is too much).
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = 0;
for ($i = 0; $i < strlen($stringSentence); $i++) {
if($stringSentence[$i] == " " || $i+1 == strlen($stringSentence)) {
echo "WordCount: $wordcount | Word: " . substr($stringSentence, $blankCharacter, $i-$blankCharacter+1) . "<br>";
$blankCharacter = $i;
$wordcount++;
}
}
echo "Total WordCount: " . ($wordcount-1);
?>
OK here is what i want to do
I have an array that contains keywords
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
and i have another array that contains my whole titles
let's say
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer's Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona','','');
so now what i want to do
is to loop my keywords array in each of the titles array element
and if there is 3 keywords in one element then do something
for example
$titiles[0] // this one has these words => Madrid , cup club
so this one is have at least 3 words of my keywords
so if each element has 3 keywords or more , then echo that array element.
any idea on how to get this working?
foreach ($titles as $t){
$te=explode(' ',$t);
$c=count(array_intersect($te,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
live demo: http://codepad.viper-7.com/7kUUEK
2 matches is your current max
if you want Madrid to match madrid
$keywords=array_map('strtolower', $keywords);
foreach ($titles as $t){
$te=explode(' ',$t);
$comp=array_map('strtolower', $te);
$c=count(array_intersect($comp,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
http://codepad.viper-7.com/itdegA
Alternatively, you could also use substr_count() to get the number of occurances. Consider this example:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.',"Cristiano Ronaldo is World Soccer's Player of the Year 2013.","Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona",'','');
$count = 0;
$data = array();
foreach($titles as $key => $value) {
$value = strtolower($value);
$keys = array_map('strtolower', $keywords);
foreach($keys as $needle) {
$count+= substr_count($value, $needle);
}
echo "In title[$key], the number of occurences using keywords = " .$count . '<br/>';
$count = 0;
}
Sample Output:
In title[0], the number of occurences using keywords = 3
In title[1], the number of occurences using keywords = 2
In title[2], the number of occurences using keywords = 2
In title[3], the number of occurences using keywords = 0
In title[4], the number of occurences using keywords = 0
Fiddle
Simpler with array_intersect:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer\'s Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona');
foreach($titles as $title) {
if (count(array_intersect(explode(' ',strtolower($title)), $keywords)) >= 3) {
//stuff
}
}
I am trying to write a php script for my site that will allow me to use spin syntax to inject words (pre defined) into a paragraph. I am just not sure how to do it multiple times in one script. For instance, I have a paragraph like this:
The {fat|pudgy|lazy} dog {sleeps|rest|poops} all day long.
I am trying to make the script access each group of text in between the {text 1|text 2} curly brackets and then randomly choose which variable to use (separated by pipes). When it is done it will spit out many variations of the string such as:
The fat dog sleeps all day long.
The lazy dog poops all day long.
Etc.
I am able to access the first instance of the text with in the {} brackets and then spin that, but I just dont know how to do it multiple times in one fell swoop. Anyone ever done this?
Here is my script to access the first instance of text in between the first two {} brackets.
function get_between ($text, $s1, $s2) {
$spinText = "";
$pos_s = strpos($text,$s1);
$pos_e = strpos($text,$s2);
for ( $i=$pos_s+strlen($s1) ; (( $i<($pos_e)) && $i < strlen($text)) ; $i++ ) {
$spinText .= $text[$i];
}
return $spinText;
}
$str = "The {fat|pudgy|lazy} dog {sleeps|rest|poops} all day long.";
$spinTextFinal = get_between($str,"{","}");
$spinTextFinalExplode = explode("|",$spinTextFinal);
print_r($spinTextFinalExplode);
Solution 1: You can use preg_replace_callback
$str = "The {fat|pudgy|lazy} dog {sleeps|rest|poops} all day long.";
echo "<pre>";
for($i = 0; $i < 10; $i ++) {
echo get_between($str, "{", "}"), PHP_EOL;
}
Output
The fat dog rest all day long.
The lazy dog poops all day long.
The fat dog sleeps all day long.
The lazy dog sleeps all day long.
The lazy dog poops all day long.
The lazy dog poops all day long.
The pudgy dog rest all day long.
The pudgy dog rest all day long.
The fat dog poops all day long.
The fat dog rest all day long.
Modified function
function get_between($text, $s1, $s2) {
$text = preg_replace_callback(sprintf("/%s(.*?)%s/", preg_quote($s1), preg_quote($s2)), function ($m) {
$l = explode("|", $m[1]);
return $l[array_rand($l)];
}, $text);
return $text;
}
Solution 2 Just use arrays
$arr1 = array("fat","pudgy","lazy");
$arr2 = array("sleeps","rest","poops");
$str = "The %s dog %s all day long.";
echo sprintf($str,$arr1[array_rand($arr1)],$arr1[array_rand($arr1)]);
Figured it out :)
$str = "The {fat|pudgy|lazy} dog {sleeps|rest|poops} all day long.";
$start_string ='{';
$stop_string = '}';
preg_match_all('/' . $start_string. '(.*)' . $stop_string . '/Usi' , $str, $strings);
foreach($strings[1] as &$value){
$explodePhrase = explode("|",$value);
$key = array_rand($explodePhrase);
$valueX = $explodePhrase[$key];
$string[$value] = $valueX;
}
foreach($string as $key => $value){
$str = str_replace($key,$value,$str);
$str = $str;
}
echo $str;
I want to bring the last three words of a string to its beginning. For example, these two variables:
$vari1 = "It is a wonderful goodbye letter that ultimately had a happy ending.";
$vari2 = "The Science Museum in London is a free museum packed with interactive exhibits.";
Should become:
"A happy ending - It is a wonderful goodbye letter that ultimately had."
"With interactive exhibits - The Science Museum in London is a free museum packed."
Exploding, rearranging, and then imploding should work. See the example here
$array = explode(" ", substr($input_string,0,-1));
array_push($array, "-");
for($i=0;$i<4;$i++)
array_unshift($array, array_pop($array));
$output_string = ucfirst(implode(" ", $array)) . ".";
$split = explode(" ",$vari1);
$last = array_pop($split);
$last = preg_replace("/\W$/","",$last);
$sec = array_pop($split);
$first = array_pop($split);
$new = implode(" ",array(ucfirst($first),$sec,$last)) . " - " . implode(" ",$split) . ".";
Or similar should do the trick.
Make sure to love me tender. <3
function switcheroo($sentence) {
$words = explode(" ",$sentence);
$new_start = "";
for ($i = 0; $i < 3; $i++) {
$new_start = array_pop($words)." ".$new_start;
}
return ucfirst(str_replace(".","",$new_start))." - ".implode(" ",$words).".";
}
This will get you the exact same output that you want in only 2 lines of code
$array = explode(' ', $vari1);
echo ucfirst(str_replace('.', ' - ', join(' ', array_merge(array_reverse(array(array_pop($array), array_pop($array), array_pop($array))), $array)))) . '.';
I have some sentences. I have to choose the sentences that consist of more than 6 words. and then they will be inserted to database.
<?php
require_once 'conf/conf.php';
$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);
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save = $sentence. ".";
$sql = mysql_query("INSERT INTO tb_name VALUES('','$save')");
}
}
?>
The result is only the second sentence that inserted in database => 'Do you read poetry while flying? Many people find it relaxing to read on long flights'. whereas the third sentence also should be inserted. please help me, thank you : )
Here is the solution you're looking for. You cannot add multiple rows since your ID value is left unspecified and it is the key into the table. Since you want to add the sentences to the same row, you need to execute one query.
$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) {
$sql = mysql_query("INSERT INTO tb_name VALUES('','" . implode( ' ', $save) . "')");
}
Now, both sentences will be inserted into the same row in the database, separated by a space. You can change what they're separated by if you modify the first parameter to implode().
The query that gets generated is this:
INSERT INTO tb_name VALUES('',' 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.')
Replace:
$sentences = explode(".", $text);
with this:
$newSentences = array();
$sentences = preg_split("/(\.|\?|\!)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$odd = false;
foreach($sentences as $sentence) {
$sentence = trim($sentence);
if($sentence != '') {
if(!$odd) {
$newSentences[] = $sentence;
} else {
$newSentences[count($newSentences) - 1] .= $sentence;
}
$odd = !$odd;
}
}
It separates sentences ending in with . or ? or !. The foreach just reassembles the sentences.
Example here: http://codepad.org/kk3PsVGP