I have a list of dozens of simple sentences/strings. Each sentence contains a special keyword. My task is to make sure this special keyword is ALWAYS as the first word of the sentence.
Let's assume my special keyword is: dog.
Example sentences BEFORE:
$string1='my dog is eating soup';
$string2='where have you seen my dog last time';
$string3='this little dog barks a lot';
$string4='most cats are better than my dog';
Sentences that should be AFTER:
dog my is eating soup
dog where have you seen my last time
dog this little barks a lot
dog most cats are better than my
I see there is str_shuffle PHP function but it shuffles words in a string randomly; I need to make sure that my special keyword (dog) is always first in sentence. And ideally this function should be as fast as possible since there are lots of such operations to complete.
NOTE - I only need an example on how to do it on one sentence, not all..
This should work for you:
Just simply remove the keyword in the string with str_replace()
and append it at the start of the string, e.g.
<?php
$str = "my dog is eating soup";
$keyword = "dog";
echo $newString = $keyword . " " . str_replace($keyword, "", $str);
?>
output:
dog my is eating soup
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments