Replacing a reoccurring value in a string with random values - php

Today is a sunny day
I would like to take the is and replace that with three random terms.
So: Today {was|wasn't|isn't} a sunny day
However, if is is in another string with five occurrences (say an article), I would like to replace each occurrence with a random value from {was|wasn't|isn't}
How can I accomplish this?
So far, I know you must use str_replace, with an array inside a foreach loop. However I can't get it working.
Any help with be greatly appreciated.
Thanks!

Try this:
$replacements = array("was", "wasn't", "isn't");
preg_replace("/\wis\w/e", "$replacements[array_rand($replacements)]", $text);
The 'e' modifier in the searched regular expression causes the replacement string to be evaluated as PHP code. array_rand is then used to pick a random key from $replacements

Alternative way...
$str = "Today is a sunny day";
$findme = "is";
$arr = array("was","wasn't","isn't");
$tmp = explode("is",$str);
$str = $tmp[0];
for($i=1;$i<count($tmp);$i++)
$str .= array_rand($arr) . $tmp[$i];

See this wack solution here
$d = array("was","wasn't","isn't");
$st = "Today is a sunny day, is it not?";
$arr = explode(" ", $st);
for($i=0;$i<count($arr);$i++){
if ($arr[$i] == "is"){
$r = rand(0, 2);
$arr[$i] = $d[$r];
}
}
foreach($arr as $v){
echo $v." ";
}
?>
Outputs
Today wasn't a sunny day, was it not?

Related

PHP Spliting then Combining

for example I have a string like this:
$string = 'eat|drink today|tomorrow';
from above string I want to get the result
eat today, eat tomorrow, drink today, drink tomorrow,
what I have to do? I try with split but not so good the result. thanks.
One way is with leveraging explode & implode and as we are explicit here (you know values and size) this would work.
Might be a quicker nicer way with a regular expression to get the first string instantly split, but this was a solution that came in mind at first glance.
$string = 'eat|drink today|tomorrow';
// First split the string by the space between them, then by the pipe in separate arrays.
$removedSpace = explode(' ', $string);
// The action items.
$actions = explode('|', $removedSpace[0]);
// The periods/time of day items.
$dayPeriods = explode('|', $removedSpace[1]);
$final = [];
// Loop through actions and for each day period, generate the string.
foreach ($actions as $action) {
foreach ($dayPeriods as $dayPeriod) {
$final[] = $action . ' ' . $dayPeriod;
}
}
$finalString = implode(', ', $final); // Your desired result in string format without last comma.
[EDIT]
I was writing up my reply while the first reply was published.
Feel free to delete this.
[/EDIT]
You can use explode a several times:
$string = 'eat|drink today|tomorrow';
$tmp = explode(' ',$string); // eat|drink today|tomorrow => [eat|drink, today|tomorrow]
$tmp1 = explode('|',$tmp[0]); // eat|drink => [eat, drink]
$tmp2 = explode('|',$tmp[1]); // today|tomorrow => [today, tomorrow]
foreach($tmp1 as $eat){
foreach($tmp2 as $today){
echo "$eat $today, ";
}
}
Demo
Output:
eat today, eat tomorrow, drink today, drink tomorrow,

php string manipulation issues

I have the following string...
$string = "True is True (5-7 years)";
what I want is to get - TiT(5-7 years)
I have tried the following code but no luck...
$string = "True is True (5-7 years)";
$explodedString = explode(" ",$string);
for($i = 0; $i < 4; $i++){
$tempString = substr($explodedString[$i], 0, 1);
$finalString .= $tempString;
}
In short, I need the first three words of its initials and the remaining in bracket is as it is like this.... TiT(5-7 years). how?
This a good case for using regular expressions:
$str = 'True is True (5-7 years)';
preg_match_all('~\([^()]*\)|\b\w~', $str, $matches);
echo implode("", $matches[0]); // TiT(5-7 years)
Regex breakdown:
\([^()]*\) Match anything inside parentheses including themselves
| Or
\b\w Match first word character from a word
Your loop is going one element too far. If you want the first letter of the first 3 words, it should be $i < 3.
Then you should use array_slice() and implode() to concatenate the rest of the array.
for ($i = 0; $i < 3; $i++) {
$finalString .= $explodedString[$i][0];
}
$finalString .= implode(' ', array_slice($explodedString, 3));
DEMO
$string = "True is True (5-7 years)";
$new_string = preg_replace('/^([a-z])[a-z]+ ([a-z])[a-z]+ ([a-z])[a-z]+ (\(.+\))$/i', '$1$2$3$4', $string);
First of all.
Create an empty variable. That will be your final result
$result="";
Then youse foreach to loop your explode string.
At every part chech the first character.
If it's not ( add the first char onto the result variable.
else add the whole array element onto the result variable
foreach(explodedString as $t){
If($t[0] !="("){$result.=$t[0];} else{$result.=$t;}
}
At the end of the loop you will get what you wanted
echo $result;

count the occurrences of all the letters in a string PHP

I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in
string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
you can do it by following way as well:
$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

PHP String into array keyed by word start

Say I have the following string
$str = "once in a great while a good-idea turns great";
What would be the best solution to creating an array with the array key being the string count of where the word(s) starts?
$str_array['0'] = "once";
$str_array['5'] = "in";
$str_array['8'] = "a";
$str_array['10'] = "great";
$str_array['16'] = "while";
$str_array['22'] = "a";
$str_array['24'] = "good-idea";
$str_array['34'] = "turns";
$str_array['40'] = "great";
As simple as the following:
str_word_count($str, 2);
what str_word_count() does is
str_word_count() — Return information about words used in a string
str_word_count() with 2 as the second argument to get the the offset; and you'd probably need to use the 3rd argument to include hyphen as well as letters in words
$str = "once in a great while a good-idea turns great";
print_r(str_word_count($str, 2));
demo:
http://sandbox.onlinephpfunctions.com/code/9e1afc68725c1472fc595b54c5f8a8abf4620dfc
Try this:
$array = preg_split("/ /",$str,-1,PREG_SPLIT_OFFSET_CAPTURE);
$str_array = Array();
foreach($array as $word) $str_array[$word[1]] = $word[0];
EDIT: Just saw Mark Baker's answer. Probably a better option than mine!
You can use preg_split (with the PREG_SPLIT_OFFSET_CAPTURE option) to split the string on the space, then use the offset it gives you to make a new array.
$str = "once in a great while a good-idea turns great";
$split_array = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
$str_array = array();
foreach($split_array as $split){
$str_array[$split[1]] = $split[0];
}

preg_replace php to replace repeated characters

So I have a list of values like that goes like this:
values: n,b,f,d,e,b,f,ff`
I want to use preg_replace() in order to remove the repeated characters from the list of values (it will be inserted to a MySQL table). b and f are repeated. ff should not count as f because it's a different value. I know that \b \b will be used for that. I am not sure on how to take out the repeated b and f values as well as the , that precedes each value.
If the list is in a string looking like the example above, a regex is overkill. This does it just as well;
$value = implode(',', array_unique(explode(',', $value)));
I agree with other commenters that preg_replace is not the way to go; but, since you ask, you can write:
$str = preg_replace('/\b(\w+),(?=.*\b\1\b)/', '', $str);
That will remove all but the last instance of a given list-element.
No need for regex for this:
join(",", array_unique(split(",", $values)))
If this list you're dealing with is a simple string, a possible solution would be like this:
function removeDuplicates($str) {
$arr = explode(',', $str);
$arr = array_unique($arr);
return implode(',', $arr);
}
$values = removeDuplicates('n,b,f,d,e,b,f,ff'); // n,b,f,d,e,ff
$str = "values: n,b,f,d,e,b,f,ff";
$arr = array();
preg_match("/(values: )([a-z,]+)/i", $str, $match);
$values = explode(",", $match[2]);
foreach($values AS $value){
if(!$arr[$value]) $arr[$value] = true;
}
$return = $match[1];
foreach($arr AS $a){
$return .= ($i++ >= 1 ? "," : "").$a;
}

Categories