Hello I have the following code:
$StyleOcc1 = substr_count(strtolower($text), strtolower("style=""));
if($StyleOcc1 < '1'){
$text = $text;
}else{
while($StyleOcc1 > '0'){
preg_match('~style="(.*?)">~', $text, $output);
$outputD = $output[1];
if($outputD != null){
$outputD = str_replace(""","",$outputD);
$outputD = str_replace(" ","",$outputD);
}
$text = str_replace($out[1], "", $text);
$text = str_replace("style="".$output[1].""","style="".$outputD.""",$text);
$StyleOcc1 -=1;
}
}
The code is supposed to find style=" in a body of text and replace it with style="+more stuff that is not relevant to the question. The problem is it does the first one perfectly but because I add style=" in, it just keeps doing the first one repeatedly. How can I make it move on to the next one when the first one is done? Thanks.
EDIT: Basically what I want is the following. I have five occurences of the same substring in a string and I want to replace the first one with the letter a and the second occurence with the letter b and so on. How do i do this?
Related
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 ;
I have a long text (3600 sentences) and I want to change the order of random sentences. There are some simple PHP script that can change the order of sentences?
You can accomplish it like this. Explode a string on the end of a sentence e.g full stop. Shuffle the array using the shuffle function. Then implode the string, adding the full stops back.
The output will be something like:
Hello, this is one sentence. This is a fifth. This is a forth. This is a second.. THis is a third
$sentences = 'Hello, this is one sentence. This is a second. THis is a third. This is a forth. This is a fifth.';
$sentencesArray = explode('.', $sentences);
array_filter($sentencesArray);
shuffle($sentencesArray);
$sentences = implode('.', $sentencesArray);
var_dump($sentences);
I constructed a solution which solves the problem for sentences ending with ".", "!" or "?". I noticed that it is not a good idea to include the very last part of the sentences array in the shuffling, because the last part is never supposed to end with the particular character we're splitting on:
"Hi.| Hello.| "
I hope you get the idea. So I shuffle all the elements except the last. And I do the work separately for ".", "?", and "!".
You should know that "...", "?!", "!!!11!!1!!" will cause big trouble. :):)
<?php
function randomizeOrderOnDelimiter($glue,$sentences){
$sentencesArray = explode($glue, $sentences);
// Get out the items to shuffle: all but the last.
$work = array();
for ($i = 0; $i < count($sentencesArray)-1; $i++) {
$work[$i] = $sentencesArray[$i];
}
shuffle($work); // shuffle them
// And put them back.
for ($i = 0; $i < count($sentencesArray)-1; $i++) {
$sentencesArray[$i] = $work[$i];
}
$sentences = implode($glue, $sentencesArray);
return $sentences;
}
$sentences = 'Hello, this is one sentence. This is a second. THis is a third. This is a forth. This is a fifth. Sixth is imperative! Is seventh a question? Eighth is imperative! Is ninth also a question? Tenth.';
$sentences = randomizeOrderOnDelimiter('.', $sentences);
$sentences = randomizeOrderOnDelimiter('?', $sentences);
$sentences = randomizeOrderOnDelimiter('!', $sentences);
var_dump($sentences);
?>
I am trying to get the number of words that a domain web page has, but I get way larger numbers than expected. For example on Google.com with my function I get 180 words, and counted manually there are about 30. I noticed that it also includes the words from style tags and javascript tags, that is a bit odd. I also checked this http://www.seoreviewtools.com/bulk-web-page-word-count-checker/ and it's counting only 6.
Where am I mistaking?
function get_page_stats($domain) {
$str = file_get_contents($domain);
$str = strip_tags(strtolower($str));
$words = str_word_count($str, 1);
$words = array_count_values($words); // added as per Avinash Babu answer
var_dump($words);
}
get_page_stats('http://google.com');
You can use array_count_values() for this.
A simple example
<?php
$str = '<h1>Hello</h1> this will show word count of all word used this time... hello!';
print_r(array_count_values(str_word_count(strip_tags(strtolower($str)), 1)));
I managed to filter very well by removing the style tags and the script tags from the entire web page.
function get_page_stats($domain) {
$str = file_get_contents($domain);
$str = preg_replace('/<style\\b[^>]*>(.*?)<\\/style>/s', '', $str);
// remove everything between the style tags
$str = preg_replace('/<script\\b[^>]*>(.*?)<\\/script>/s', '', $str);
// remove everything between the script tags
$str = strip_tags(strtolower($str));
// remove html tags
$words = str_word_count($str, 1);
$words = array_count_values($words);
// count the words
var_dump($words);
}
here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);
I want to display just two lines of the paragraph.
How do I do this ?
<p><?php if($display){ echo $crow->content;} ?></p>
Depending on the textual content you are referring to, you might be able to get away with this :
// `nl2br` is a function that converts new lines into the '<br/>' element.
$newContent = nl2br($crow->content);
// `explode` will then split the content at each appearance of '<br/>'.
$splitContent = explode("<br/>",$newContent);
// Here we simply extract the first and second items in our array.
$firstLine = $splitContent[0];
$secondLine = $splitContent[1];
NOTE - This will destroy all the line breaks you have in your text! You'll have to insert them again if you still want to preserve the text in its original formatting.
If you mean sentences you are able to do this by exploding the paragraph and selecting the first two parts of the array:
$array = explode('.', $paragraph);
$2lines = $array[0].$array[1];
Otherwise you will have to count the number of characters across two lines and use a substr() function. For example if the length of two lines is 100 characters you would do:
$2lines = substr($paragraph, 0, 200);
However due to the fact that not all font characters are the same width it may be difficult to do this accurately. I would suggest taking the widest character, such as a 'W' and echo as many of these in one line. Then count the maximum number of the largest character that can be displayed across two lines. From this you will have the optimum number. Although this will not give you a compact two lines, it will ensure that it can not go over two lines.
This is could, however, cause a word to be cut in two. To solve this we are able to use the explode function to find the last word in the extracted characters.
$array = explode(' ', $2lines);
We can then find the last word and remove the correct number of characters from the final output.
$numwords = count($array);
$lastword = $array[$numwords];
$numchars = strlen($lastword);
$2lines = substr($2lines, 0, (0-$numchars));
function getLines($text, $lines)
{
$text = explode("\n", $text, $lines + 1); //The last entrie will be all lines you dont want.
array_pop($text); //Remove the lines you didn't want.
return implode("<br>", $text); //Implode with "<br>" to a string. (This is for a HTML page, right?)
}
echo getLines($crow->content, 2); //The first two lines of $crow->content
Try this:
$lines = preg_split("/[\r\n]+/", $crow->content, 3);
echo $lines[0] . '<br />' . $lines[1];
and for variable number of lines, use:
$num_of_lines = 2;
$lines = preg_split("/[\r\n]+/", $crow->content, $num_of_lines+1);
array_pop($lines);
echo implode('<br />', $lines);
Cheers!
This is a more general answer - you can get any amount of lines using this:
function getLines($paragraph, $lines){
$lineArr = explode("\n",$paragraph);
$newParagraph = null;
if(count($lineArr) > 0){
for($i = 0; $i < $lines; $i++){
if(isset($lines[$i]))
$newParagraph .= $lines[$i];
else
break;
}
}
return $newParagraph;
}
you could use echo getLines($crow->content,2); to do what you want.