How to shuffle words in a sentence? - php

I have a simple form where I can enter a sentence. When I submit the form I want to shuffle the words (not characters). This is what I did so far, but it's not mixing the words:
if (isset($_POST['sentence'])) {
$original_sentence = $_POST['sentence'];
} else {
die ('Give me a sentence!');
}
$words = explode( " / ", $original_sentence );
foreach($words as $word) {
array_rand($words);
echo $word;
}

you can explode, shuffle and implode:
$original_sentence = "i am a simple sentence";
$words = explode( " ", $original_sentence );
shuffle($words);
echo implode(" ",$words);
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
http://php.net/manual/en/function.shuffle.php

Related

Replace word with stars (exact length)

am trying to replace a word in a string BUT i want to get the word found in the function and replace it with a word with stars with the exact length ?
Is this possible or do i need to do this in some other way ?
$text = "Hello world, its 2018";
$words = ['world', 'its'];
echo str_replace($words, str_repeat("*", count(FOUND) ), $text);
You could use a regular expression to do that :
$text = preg_replace_callback('~(?:'.implode('|',$words).')~i', function($matches){
return str_repeat('*', strlen($matches[0]));
}, $text);
echo $text ; // "Hello *****, *** 2018"
You also could secure this using preg_quote before to use preg_replace_callback() :
$words = array_map('preg_quote', $words);
EDIT : The following code is another way, that use a foreach() loop, but prevent unwanted behaviors (replacing part of words), and allows multi-bytes characters:
$words = ['foo', 'bar', 'bôz', 'notfound'];
$text = "Bar&foo; bAr notfoo, bôzo bôz :Bar! (foo), notFOO and NotBar or 'bar' foo";
$expt = "***&***; *** notfoo, bôzo *** :***! (***), notFOO and NotBar or '***' ***";
foreach ($words as $word) {
$text = preg_replace_callback("~\b$word\b~i", function($matches) use ($word) {
return str_ireplace($word, str_repeat('*', mb_strlen($word)), $matches[0]);
}, $text);
}
echo $text, PHP_EOL, $expt ;
Another approach:
$text = "Hello world, its 2018";
$words = ['world', 'its'];
$f = function($value) { return str_repeat("*", strlen($value)) ; } ;
$replacement = array_map($f, $words);
echo str_replace($words, $replacement, $text);
You can try this :
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018
Is it what you are looking for?
You can go like this..
$text = "Hello crazy world, its 2018";
$words = ['world', 'its'];
array_walk($words,"replace_me");
function replace_me($value,$key)
{
global $text;
$text = str_replace($value,str_repeat("*",strlen($value)),$text);
}
echo $text;
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018

Edit all odd words in string to upper case

I need to edit all odd words to upper case.
Here is sample of imput string:
very long string with many words
Expected output:
VERY long STRING with MANY words
I have this code, but it seams to me, that I can do it in better way.
<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(\S[\w]*)/";
foreach($lines as $value)
{
$words = NULL;
$fin_str = NULL;
preg_match_all($pattern, $value, $matches);
for($i = 0; $i < count($matches[0]); $i = $i + 2){
$matches[0][$i] = strtoupper($matches[0][$i]);
$fin_str = implode(" ", $matches[0]);
}
echo $fin_str ."<br>";
P.S. I need to use only preg_match function.
Here's a preg_replace_callback example:
<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/',
function($matches) {
return strtoupper($matches[1]) . ' ' . $matches[2];
}, $str);
print $newStr;
// VERY long STRING with MANY words
?>
You only need to match the repeating pattern: /([^ ]+) +([^ ]+)/, a pair of words, then preg_replace_callback recurses over the string until all possible matches are matched and replaced. preg_replace_callback is necessary to call the strtoupper function and pass the captured backreference to it.
Demo
If you have to use regular expressions, this should get you started:
$input = 'very long string with many words';
if (preg_match_all('/\s*(\S+)\s*(\S+)/', $input, $matches)) {
$words = array();
foreach ($matches[1] as $key => $odd) {
$even = isset($matches[2][$key]) ? $matches[2][$key] : null;
$words[] = strtoupper($odd);
if ($even) {
$words[] = $even;
}
}
echo implode(' ', $words);
}
This will output:
VERY long STRING with MANY words
You may don't need regex simply use explode and concatenate the string again:
<?php
function upperizeEvenWords($str){
$out = "";
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++){
if (!($i%2)){
$out .= strtoupper($arr[$i])." ";
}
else{
$out .= $arr[$i]." ";
}
}
return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);
Checkout this DEMO

Remove word from a string

I have a csv file that contains company names. I would want to match it against my database. In order to have a cleaner and nearer matches, I am thinking of eliminating some company suffixes like 'inc', ' inc', ', inc.' or ', inc'. Here's my sample code:
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc."," Inc.",", Inc.",", Inc"," Inc");
foreach ($wordlist as &$word) {
$word = '/\b' . preg_quote($word, '/') . '\b/';
}
$string = preg_replace($wordlist, '', $string);
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;
My problem here is that the 'inc.' doesn't get removed. I'm guessing it has something to do with the preq_quote. But I just can't figure out how to solve this.
Try this :
$string = 'Inc incorporated inc.';
$wordlist = array("Inc","inc.");
foreach ($wordlist as $word) {
$string =str_replace($word, '', $string);
}
echo $string;
OR
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc","inc.");
$string = str_replace($wordlist, '', $string);
echo $string;
This will output as 'corporated'...
If you want "Incorporated" as result, make the "I" is small.. and than run my above code (first one)...
Try this. It may involve type juggling at some point, but will have your desired result
$string = 'Inc Incorporated inc.';
$wordlist = array('Inc', 'inc.');
$string_array = explode(' ', $string);
foreach($string_array as $k => $a) {
foreach($wordlist as $b) {
if($b == $a){
unset($string_array[$k]);
}
}
$string_array = implode('', $string_array);
You can use this
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc "," inc.");
$foo = str_replace($wordlist, '', $string);
echo $foo;
Run this code here
This will work for any number of elements in array...
$string = 'Inc Incorporated inc.';
$wordlist = array("Inc");
foreach($wordlist as $stripped)
$string = preg_replace("/\b". preg_quote($stripped,'/') ."(\.|\b)/i", " ", $string) ;
$foo = preg_replace('/\s+/', ' ', $string);
echo $foo;

PHP string-manipulation

I have a string, for example:
"abc b, bcd vr, cd deb"
I would like to take the first word of this string until every single point in this case would result in "abc bcd cd". My code unfortunately does not work. Can you help me?
<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay);
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo $first[$ii];
$ii= $ii+1;
}
?>
<?php
function get_first_word($string)
{
$words = explode(' ', $string);
return $words[0];
}
$string = 'abc b, bcd vr, cd deb';
$splitted = explode(', ', $string);
$new_splitted = array_map('get_first_word', $splitted);
var_dump($new_splitted);
?>
<?php
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num= count($ay);
$ii= 0;
while ($ii!=$num){
$first = explode(" ", $ay[$ii]);
echo ($ii == 0) ? $first[0] . " " : $first[1] . " ";
$ii= $ii+1;
}
?>
You should only take $first[$ii] when you get first element becouse explode take this whan is before space at first element.
$string= "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
foreach($ay as $words) {
$words = explode(' ', $words);
echo $words[0];
}
Using array_reduce():
$newString = array_reduce(
// split string on every ', '
explode(", ", $string),
// add the first word of every comma section to the partial string
function(&$result, $item){
$result .= array_shift(explode(" ", $item)) . " ";
return $result;
}
);

Php replace and concat

I need to replace and concat some values in a random string, i store the values in an array.
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
If one or more array values matches the random string then i need a replace like this:
$replacedString = "A #dog in a #forest";
Can someone help me?
Thx.
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "#$word " : "$word ";
}
echo $replacedString; // A #dog in a #forest
foreach($search as $word)
{
$randomString = str_replace($word,"#".$word,$randomString);
}
Not sure if I understand what you're trying to do correctly but have a look at str_replace() function
and try something like
foreach($search as $string)
{
$replacement[] = "#".$search;
}
$new_string = str_replace($search, $replacement, $randomString);
This should work for you:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "#$word";
}
}
$replacedString = implode(" ", $words);

Categories